# Shoot a bullet towards cursor - top down 2d

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.

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