0

如果尝试搜索互联网但我找不到答案。

我正在尝试计算从第一个向量看到的 2 个向量之间的角度。

因此,如果向量 1 位于 0,0,向量 2 位于 1,1,则航向将为 45。

在 1,0 将是 90。

在 -1,0 为 270。

有没有一个简单的解决方案来创建这个?

4

5 回答 5

1

我无法在 atm 测试它,但这应该可以:

double getHeading(Vector2 a, Vector2 b)
{
    double x = b.x - a.x;
    double y = b.y - a.y;
    return Math.Atan2(y, x) * (180 / Math.PI);
}
于 2016-08-06T12:37:47.070 回答
0

给定一个偏移向量(例如相对于 0,0,0)

float resultInDegrees = (360 + Mathf.Atan2(rotateVector.x, rotateVector.z) * (180 / Mathf.PI)) % 360;

请注意,我们将添加 360 并获取结果的模数,否则您将得到 0 - 180,然后是负角。这会将 -1 度转换为 359 度,正如原始海报所要求的那样。

于 2020-11-20T20:01:22.680 回答
0

这不是 Unity,这是一道数学题。

您需要使用向量点乘法。它是统一的,等于向量的长度乘以它们之间夹角的余弦的乘积,所以你很容易从中得到向量之间的夹角。当然,unity 有一个内置的功能

由于每帧都会执行许多涉及向量的操作,因此了解您正在运行的代码的性能影响会有所帮助。可悲的是,这个问题的其他解决方案在计算上更加复杂。另外,请记住,您通常不需要角度本身:角度的余弦实际上很容易处理。

当然,这个答案不包括 270 度的情况。然而,对于这种应用,四元数更适合。基本上,270 的情况要求你知道向上的向量来计算它,而向量本身(作为数学抽象)不包含该信息——所以,在数学层面上,你没有任何方法可以区分向量它们之间有 270 度和 90 度。

因此,如果您真的需要 270 的情况,请从向量创建四元数(顺便说一下,您可以在此处看到向上向量是一条不同的信息),然后计算它们之间的角度。与向量不同,创建四元数是为了处理旋转和方向,而 Unity 已为此实现了所有功能。

于 2016-08-07T08:36:52.613 回答
-2

感谢您的回复,我决定进行手动计算。对于任何在我之后发现这个问题的人,我就是这样做的:

double calculateHeading(Transform target){
    double newHeading = 0;

    Vector3 vectorToTarget = target.position - transform.position;
    double x = vectorToTarget.x;
    double y = vectorToTarget.y;

    if (x == 0 && y > 0) {
        newHeading = 0;
    } else if (x == 0 && y < 0) {
        newHeading = 180;
    } else if (x > 0 && y == 0) {
        newHeading = 90;
    } else if (x < 0 && y == 0) {
        newHeading = 270;
    } else if (y < 0) {
        newHeading = 180 + (Mathf.Rad2Deg * Mathf.Atan (vectorToTarget.x / vectorToTarget.y));
    } else if (y > 0) {
        newHeading = 360 + (Mathf.Rad2Deg * Mathf.Atan (vectorToTarget.x / vectorToTarget.y));
    }

    if (newHeading > 360) {
        newHeading -= 360;
    } else if (newHeading < 0) {
        newHeading += 360;
    }

    return newHeading;
}
于 2016-08-07T11:36:58.363 回答
-2

兄弟,你试过用谷歌吗?我刚刚搜索了“两个向量之间的统一角度”并找到了官方文档。

https://docs.unity3d.com/ScriptReference/Vector3.Angle.html

var angle = Vector3.Angle(Vector3 from, Vector3 to); 

或者在你的情况下

var angle = Vector2.Angle(Vector2 from, Vector2 to); 
于 2016-08-16T03:19:27.850 回答