4
\$\begingroup\$

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.

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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.

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .