找到两个向量之间的角度

时间:2014-08-28 09:53:37

标签: c# xna angle

我已经阅读了一些关于两个向量之间角度的重复答案,但我仍然坚持我的问​​题。我有两个向量,我希望它们之间的角度始终为90度。为了实现这一点,我需要找到它们之间的角度,这样我就可以减去或加上正确的度数,使它们之间的角度始终为90度。

enter image description here

图片说明了精灵和两个向量。我如何找到它们之间的角度A?我试图使用这个代码来获得两个向量之间的角度,但我一定错过了一些东西,因为我没有得到正确的结果:

        public float GetAngleBetween (Vector2 A, Vector2 B)
    {
        float DotProd = Vector2.Dot (A, B);
        float Length = A.Length () * B.Length ();
        return (float)MathHelper.ToDegrees ((float)Math.Acos (DotProd/Length));
    }

欢迎任何意见,并提前感谢您的任何答案。

3 个答案:

答案 0 :(得分:1)

以弧度表示的实际角度为

Math.ACos(Vector2.Dot(a, b));

确保a和b是规范化的向量,否则结果会非常奇怪。

答案 1 :(得分:0)

我认为你可能正在寻找用于计算两个向量的乘积的Vector2.Dot方法,并且可以用于角度计算。

例如:

// the angle between the two vectors is less than 90 degrees. 
Vector2.Dot(vector1.Normalize(), vector2.Normalize()) > 0 

// the angle between the two vectors is more than 90 degrees. 
Vector2.Dot(vector1.Normalize(), vector2.Normalize()) < 0 

// the angle between the two vectors is 90 degrees; that is, the vectors are orthogonal. 
Vector2.Dot(vector1.Normalize(), vector2.Normalize()) == 0 

// the angle between the two vectors is 0 degrees; that is, the vectors point in the same direction and are parallel. 
Vector2.Dot(vector1.Normalize(), vector2.Normalize()) == 1 

// the angle between the two vectors is 180 degrees; that is, the vectors point in opposite directions and are parallel. 
Vector2.Dot(vector1.Normalize(), vector2.Normalize()) == -1 

这是您正在寻找的,还是您需要准确的角度?

答案 2 :(得分:0)

如果我理解您的问题图表和评论,则Dot产品和Acos不是您需要的唯一信息。您还需要考虑精灵何时不在(0,0)。

float angleInRadians = (float) Math.Acos(Vector2.Dot(Vector2.Normalize(vector1 - spritePosition), Vector2.Normalize(vector2 - spritePosition)));

int angleInDegrees = MathHelper.ToDegrees(angleInRadians);