是第二个角

问题描述 投票:0回答:2

我需要知道另一个角度是在源角的右边还是左边。

我试图减去角度并得到它们的绝对值,但范围是从 -180 到 180,这意味着当我转到 180 和转到 -180 时,它会给我相反的答案。

如果您想知道这是干什么用的,那是我正在开发的一款 Java 游戏,其中有一个由鼠标控制的坦克炮塔。

java math game-engine game-physics angle
2个回答
4
投票

这取决于你的角度是否指定顺时针或逆时针方向的旋转。如果您朝坦克炮塔的方向看,那么如果您需要顺时针旋转炮塔以尽快指向它,则物体位于右侧,如果您需要逆时针旋转,则物体位于左侧。

很明显,你可以向相反方向旋转以“绕远路”:如果一个物体向右旋转 10 度,那么你可以顺时针旋转 10 度或逆时针旋转 350 度以指向它。但是让我们只考虑最短的方法,假设角度是按顺时针方向指定的:

// returns 1 if otherAngle is to the right of sourceAngle,
//         0 if the angles are identical
//         -1 if otherAngle is to the left of sourceAngle
int compareAngles(float sourceAngle, float otherAngle)
{
    // sourceAngle and otherAngle should be in the range -180 to 180
    float difference = otherAngle - sourceAngle;

    if(difference < -180.0f)
        difference += 360.0f;
    if(difference > 180.0f)
        difference -= 360.0f;

    if(difference > 0.0f)
        return 1;
    if(difference < 0.0f)
        return -1;

    return 0;
}

减去角度后,结果可以在-360(-180减180)到360(180减-180)的范围内。您可以通过加减 360 度将它们置于 -180 到 180 的范围内,然后与零进行比较并返回结果。

绝对值在 180 到 360 之间的角度对应“远距离”旋转,加上或减去 360 将它们转换为“近距离”。例如 -350 度顺时针方向(即逆时针方向 350 度)加上 360 等于顺时针方向 10 度。

如果指定的角度是逆时针方向,则返回值的含义相反(1表示左,-1表示右)


0
投票

我正在回顾我的一个旧项目,发现了一些有趣的东西,我认为这些东西可能对这个或其他情况有用。是一个可以取任意两个角度,输出-179到180范围内的角度差和方向的表达式。

(((B-A+180)%360-360)%360+180)

// =0 if the Angles are Identical,
// <0 if TargetAngle is to the left of SourceAngle,
// >0 if TargetAngle is to the right of SourceAngle.
// if AngleToAngle == 180, then they are Parallel Angles.
// SourceAngle and TargetAngle can be any Angle.

function AngleToAngle(SourceAngle, TargetAngle) {
return (((TargetAngle-SourceAngle+180)%360-360)%360+180); }

//multiply return by -1 if left and right needs to be flipped:
//return -1*(((TargetAngle-SourceAngle+180)%360-360)%360+180); }

部分例子如下:

AngleToAngle(20,60) = 40
AngleToAngle(90,0) = -90
AngleToAngle(-90,350) = 80
AngleToAngle(45,270) = -135
AngleToAngle(145,525) = 20

//Note: the Modulo used here is the one in Java, C and Haxe. (-90 % 360 = -90)
//Not the same to the Modulo's used in Python and Ruby. (-90 % 360 = 270)
© www.soinside.com 2019 - 2024. All rights reserved.