I have a game where there is a Player
and some enemies
. These enemies, just as the player itself, can shoot bullets
. But the angle
of bullets don't change as it is supposed to; The newly created bullet is supposed to find the angle between itself and the player, then just go in that direction - this has to be done in 360°
.
I have followed this answer but I believe that I have done something incorrect.
currently it only goes like this:
This is the part of code which takes care of X & Y of bullets:
angle = Math.atan2(Game.getPlayerY(), Game.getPlayerX()) - Math.atan2(getY(), getX());
if (angle < 0)
angle += 2 * Math.PI;
setX((getX()+(float)(Math.sin(angle)))-Config.BulletSpeed);
setY((getY()+(float)(Math.cos(angle)))-Config.BulletSpeed);
How do I make the Bullets
go in a certain angle?
I agree with Andy's answer; you really only need a normalized vector between the two points, instead of an angle. But if you need an angle, you just form the vector between the two points, and then use
Math.atan2
:Then, if you need the x or y step, from the source to the target, normalize the vector, and then just use
velocity.x
andvelocity.y
:You don't need to derive the vector from the angle that you derived from the vector.
EDIT: As Topaco pointed out in the comments, to add a realistic touch, add the source velocity to the final velocity:
Honestly, I think you are over-complicating it by using angles. All you seem to be wanting to do is to move a bullet along the vector between the two objects at a given speed.
All you have to do for this is to normalize the vector. The length of the line between the two things is given by:
So you can use this to calculate a scale factor for the bullet speed:
Then just use this in your expression to update x and y: