Take the 2-minute tour ×

I am making a 2D topdown shooter game, in which the player's movement is controlled with WASD and gun with the mouse. I'm having a hard time figuring out how to update the position of the bullet as it moves towards the cursor.

I have the player's X and Y coords, and the cursor's X and Y coords. I need to be able to update the bullet's X and Y coords each frame based on its trajectory.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

The bullet's position changes based on it's trajectory. The trajectory you have is likely in a 2D vector? The simple update is:

UpdateBullet(Bullet bullet, float deltaTime) {
    bullet.x = bullet.x + (bullet.trajectory.x * bullet.speed * deltaTime);
    bullet.y = bullet.y + (bullet.trajectory.y * bullet.speed * deltaTime);

If instead you're asking about how to find the trajectory its self (which I'm guessing could be the case, but that's not clear in the body of your question). The trajectory is equal to the cursor position minus the player position.

Vector2f trajectory = new Vector2f(cursorPosition.x - playerPosition.x,
                                   cursorPosition.y - playerPosition.y);

And typically you'll want to normalize the trajectory so you can have consistent firing speeds.

share|improve this answer
I had the cursor and player positions reversed. Oops. –  Byte56 Apr 27 '12 at 21:40
Vector2f doesn't seem to be a javascript object..? –  Sam Apr 27 '12 at 21:41
Ah, yeah sorry, that's just pseudo code, not meant to be copy/paste. A Vector2f is just a pair of floats, perhaps you're using them already for your character position? –  Byte56 Apr 27 '12 at 21:43
Ah, ok. So: bullet.trajectory.x = cursorPosition.x - playerPosition.x, and bullet.trajectory.y = cursorPosition.y - playerPosition.y? –  Sam Apr 27 '12 at 21:49
Yep, you got it. –  Byte56 Apr 27 '12 at 21:49

Your Answer


