I'm making a top-down space shooter where the player controls a ship and can aim and shoot using the mouse cursor. How can I fire bullets from the ship at the angle from the ship to the mouse cursor?
If I understood your problem properly, you just want to shoot a bullet towards a mouse position. Here is how I would do:
First of all, you must find the movement required for the bullet to get to the mouse, like so:
Vector2 movement = mousePosition - bulletStartPosition;
Then, you should normalize it to have a vector with a length of 1 so that you can hold a vector which tells you in which direction to go, like so:
But here you have a little problem, if the direction is equal to
(0, 0) (meaning that the mouse is on the bullet start position), then you'll divide by zero, so make sure you check for that with the last piece of code:
if (movement != Vector2.Zero) movement.Normalize();
So, you've got the movement required to move towards the mouse. You have to keep a
Vector2 within your bullet class which holds the
Direction of the bullet.
What's next? You have to actually move the bullet!
In your bullet update code, do the following:
bullet.Position += bullet.Direction * bullet.Speed * gameTime.ElapsedGameTime.TotalSeconds; // multiply by delta seconds to keep a consistent speed on all computers.
bullet.Speed is a float representing the bullet's speed in units per second.
Basically, here are the things to change:
Inside you bullet class, add a
float Speed and a
When shooting, set your
mousePosition - bullet.Position and safely normalize it (by checking for equality with
When updating your bullet, do the following:
bullet.Position += bullet.Direction * bullet.Speed * gameTime.ElapsedGameTime.TotalSeconds;.
It should work.
If you're having trouble calculating the angle, you can use this:
Vector2 target = mousePos - startPos; float angle = Math.Atan2( target.Y, target.X );