Java 需要将速度转换为旋转的函数

Java 需要将速度转换为旋转的函数,java,math,physics,Java,Math,Physics,我有一个飞行物体,我想把它指向它的方向。我拥有的是物体当前的x和y速度以及旋转图像的能力。所以我需要的是一个函数,它取x和y的速度,给我旋转的角度。这是我迄今为止所拥有的功能: private float getRotation(float x, float y) { if (x == 0 && y > 0) return 90; else if (x == 0 && y < 0) return 270;

我有一个飞行物体,我想把它指向它的方向。我拥有的是物体当前的x和y速度以及旋转图像的能力。所以我需要的是一个函数,它取x和y的速度,给我旋转的角度。这是我迄今为止所拥有的功能:

private float getRotation(float x, float y)
{
    if (x == 0 && y > 0)
        return 90;
    else if (x == 0 && y < 0)
        return 270;
    else if (x > 0 && y == 0)
        return 0;
    else if (x < 0 && y == 0)
        return 180;
    else if (x == 0 && y == 0)
        return 0;
    else
        return ????;
}
private float getRotation(浮点x,浮点y)
{
如果(x==0&&y>0)
返回90;
else如果(x==0&&y<0)
返回270;
如果(x>0&&y==0),则为else
返回0;
else如果(x<0&&y==0)
返回180;
else如果(x==0&&y==0)
返回0;
其他的
回来
}
到目前为止,我所说的是正确的,除了
??
是最重要的部分之外。有人知道怎么做吗


这可能更多的是一个数学问题,但它涉及到编程,因此如果这是在错误的论坛上,我道歉。

我不得不为我编写的游戏做一些类似的事情,我最终使用极坐标。。结果如下:

if (velocity.x > 0 && velocity.y >= 0)
    angle =  atan(velocity.y/velocity.x);
else if (velocity.x > 0 && velocity.y < 0)
    angle = atan(velocity.y/velocity.x) - 2.0f*PI;
else if (velocity.x < 0)
    angle = atan(velocity.y/velocity.x) + PI;
else if (velocity.x == 0 && velocity.y > 0)
    angle = PI/2.0f;
else if (velocity.x == 0 && velocity.y < 0)
    angle = 3.0f*PI/2.0f;
if(velocity.x>0&&velocity.y>=0)
角度=atan(速度y/速度x);
否则如果(速度x>0&&velocity.y<0)
角度=atan(速度y/velocity.x)-2.0f*PI;
否则如果(速度x<0)
角度=atan(速度y/x)+PI;
else如果(velocity.x==0&&velocity.y>0)
角度=π/2.0f;
否则如果(速度x==0&&velocity.y<0)
角度=3.0f*PI/2.0f;
我写这篇文章的时候还年轻,
atan2
实际上已经足够了,但我确实想通过浏览我的旧源代码来获得乐趣


请注意:不要对浮点数使用相等的比较(
=
),请始终使用阈值(例如
abs(x)<0.01f
)进行检查,因为正如您所知,它们并不像您希望的那样精确。

我必须对我编写的游戏执行类似的操作,我最终使用极坐标。。结果如下:

if (velocity.x > 0 && velocity.y >= 0)
    angle =  atan(velocity.y/velocity.x);
else if (velocity.x > 0 && velocity.y < 0)
    angle = atan(velocity.y/velocity.x) - 2.0f*PI;
else if (velocity.x < 0)
    angle = atan(velocity.y/velocity.x) + PI;
else if (velocity.x == 0 && velocity.y > 0)
    angle = PI/2.0f;
else if (velocity.x == 0 && velocity.y < 0)
    angle = 3.0f*PI/2.0f;
if(velocity.x>0&&velocity.y>=0)
角度=atan(速度y/速度x);
否则如果(速度x>0&&velocity.y<0)
角度=atan(速度y/velocity.x)-2.0f*PI;
否则如果(速度x<0)
角度=atan(速度y/x)+PI;
else如果(velocity.x==0&&velocity.y>0)
角度=π/2.0f;
否则如果(速度x==0&&velocity.y<0)
角度=3.0f*PI/2.0f;
我写这篇文章的时候还年轻,
atan2
实际上已经足够了,但我确实想通过浏览我的旧源代码来获得乐趣


请注意:不要对浮点数使用相等的比较(
=
),请始终使用阈值(例如
abs(x)<0.01f
)进行检查,因为正如您所知,它们不像您希望的那样精确。

值得一提的是,这将替换所有OP的情况。也就是说,它自己处理所有特殊情况,包括OP不处理的无穷大等。值得一提的是,它取代了OP的所有情况。也就是说,它处理所有特殊情况本身,包括OP不处理的无穷大等。