Обнаружение самого дальнего объекта с похожим именем - PullRequest
0 голосов
/ 22 января 2019

Я хочу получить позицию самого дальнего объекта, имя которого совпадает с именем других объектов перед ним.Я сделал простую картину, чтобы проиллюстрировать мою проблему: enter image description here

Я узнал о RaycastAll, но по какой-то причине я не могу получить положение объекта интереса.

1 Ответ

0 голосов
/ 22 января 2019

В зависимости от того, где вы получаете имя, для которого вы подходите, и от того, как вы определяете происхождение луча, для вас должно работать следующее. Это предполагает, что луч создается объектом 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;
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...