检测名称相似的最远物体

时间:2019-01-22 16:00:58

标签: c# unity3d

我想获取最远的对象的位置,该对象与其前面的其他对象的名称相同。 我做了一张简单的图片来说明我的问题: enter image description here

我发现了有关RaycastAll的信息,但是由于某种原因,我无法获得感兴趣对象的位置。

1 个答案:

答案 0 :(得分:5)

取决于要在哪里获得与之匹配的名称,以及如何确定射线的原点,以下方法应该适合您。这假定光线是由运行此方法的GameObject投射的,并充当光线的来源和要匹配的名称。

public void GetFurthestObject()
{
    // Replace this with whatever you want to match with
    string nameToMatch = transform.name;

    // Initialize the ray and raycast all. Change the origin and direction to what you need.
    // This assumes that this method is being called from a transform that is the origin of the ray.
    Ray ray = new Ray(transform.position, transform.forward);
    RaycastHit[] hits;
    hits = Physics.RaycastAll(ray, float.MaxValue);

    // Initialize furthest values
    float furthestDistance = float.MinValue;
    GameObject furthestObject = null;

    // Loop through all hits
    for (int i = 0; i < hits.Length; i++)
    {
        // Skip objects whose name doesn't match.
        if (hits[i].transform.name != nameToMatch)
            continue;

        // Get the distance of this hit with the transform
        float currentDistance = Vector3.Distance(hits[i].transform.position, transform.position);

        // If the distance is greater, store this hit as the new furthest
        if (currentDistance > furthestDistance)
        {
            furthestDistance = currentDistance;
            furthestObject = hits[i].transform.gameObject;
        }
    }
}