首页 > 解决方案 > 选择许多向量和我的对象之间的最小角度

问题描述

我有一个vector3数组:

Vector3[]points

我将目标点位置存储在 Vector3 变量中:

Vector3 endPos

我需要在 Vector3 数组中获取与目标点的最小角度,并返回具有最小角度的 vector3 的索引。

我想了几个小时怎么做,但我真的不知道怎么做。我仍然是一个新人(请在 C# 中)。谢谢!

标签: c#unity3d

解决方案


您可以使用Vector3.Angle()获取两者之间的角度Vector3并迭代您的点并将最小度数及其索引存储在临时变量中。像这样的东西:

Vector3 endPos;
Vector3[] points;
private void SmallestAngle()
{
    if(points.Length <2)
    {
        Debug.LogError("There should be more than two points!");
        return;
    }
    float deg = float.PositiveInfinity;
    int index = 0;
    for (int i = 0; i < points.Length; i++)
    {

        float d = Vector3.Angle(points[i], endPos);
        if (d < deg)
        {
            deg = d;
            index = i;
        }
    }
    Debug.Log($"Smallest angle = {deg} / Index = {index}");
}

推荐阅读