Make object follow cursor

Hi. My first post on this board.

I’m creating a video game for my course and i need to find a way to make my character follow the cursor, but at it’s own speed and acceleration. It doesn’t need to involve any animations depending on the direction or speed due to the nature of the character, it just needs to make its way to any location of the cursor along with its constant animation.

Any advice would be great. Thanks in advance.

Not really an OpenGL question.

If this is a 2D game, it is pretty simple, the mouse pointer define a target, difference between character position and cursor position is the direction vector. So advance at the character speed in that direction.

For a 3D game, it is the same, the difference being that you have first to project the cursor 2D position onto the 3D geometry. Please ask if you need more details.

Your reply has helped in my understanding of what must be done (it is only 2D), but i’m not sure how to go about it. Which functions do i need to be using? So far, i have it simply moving with the cursor. It’s just it’s own rate of movement i want to calibrate.

Well there is no “function” at all, you can code this all by yourself easily :slight_smile:
Basic vector math, all using same units :
Cx,Cy : character position to be computed for current frame
Ox,Oy : character position at previous frame
Mx,My : mouse position
V : constant character speed (units/second)
dt : time between the 2 previous frames (find it for example with GLUT_ELAPSED_TIME)

Overall formula to compute new position :
C = O + OM/magnitude(OM) * V * dt
OM/magnitude(OM) is an unit length vector pointing in the direction of the mouse
Implementation :
D = OM


Dx = Mx-Ox
Dy = My-Oy


Cx = Ox + Dx / sqrt(Dx*Dx+Dy*Dy) * V * dt
Cy = Oy + Dy / sqrt(Dx*Dx+Dy*Dy) * V * dt

… just make a special case when O==M, otherwise, divide by zero :slight_smile: