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.


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.

| improve this answer | |
  • \$\begingroup\$ I had the cursor and player positions reversed. Oops. \$\endgroup\$ – MichaelHouse Apr 27 '12 at 21:40
  • \$\begingroup\$ Vector2f doesn't seem to be a javascript object..? \$\endgroup\$ – Sam Apr 27 '12 at 21:41
  • \$\begingroup\$ 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? \$\endgroup\$ – MichaelHouse Apr 27 '12 at 21:43
  • \$\begingroup\$ Ah, ok. So: bullet.trajectory.x = cursorPosition.x - playerPosition.x, and bullet.trajectory.y = cursorPosition.y - playerPosition.y? \$\endgroup\$ – Sam Apr 27 '12 at 21:49
  • \$\begingroup\$ Yep, you got it. \$\endgroup\$ – MichaelHouse Apr 27 '12 at 21:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.