atan2 - find angle between two points (360deg)

◇◆丶佛笑我妖孽 提交于 2020-01-16 02:05:24

问题


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.

because this is what happens:

and this is how it should be:

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?


回答1:


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:

double dx = Game.getPlayerX() - getX();
double dy = Game.getPlayerY() - getY();
double len = Math.hypot(dx, dy);

So you can use this to calculate a scale factor for the bullet speed:

double s = Config.BulletSpeed / len;

Then just use this in your expression to update x and y:

setX((getX()+dx*s);
setY((getY()+dy*s);



回答2:


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:

let velocity = new Vector(target.x - source.x, target.y - source.y);
let angle = Math.atan2(velocity.y, velocity.x);

Then, if you need the x or y step, from the source to the target, normalize the vector, and then just use velocity.x and velocity.y:

// normalize
let magnitude = Math.sqrt(velocity.x*velocity.x + velocity.y*velocity.y);  // distance formula for length of vector
velocity.x /= magnitude;
velocity.y /= magnitude;

// scaled to speed you want
velocity.x *= SPEED;
velocity.y *= SPEED;

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:

velocity.x += source_velocity.x
velocity.y += source_velocity.y


来源:https://stackoverflow.com/questions/52344061/atan2-find-angle-between-two-points-360deg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!