如何使用一个光线投射并击中多个游戏对象?

How can use one raycast and to hit multiple gameobjects?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OnMouseOverEvent : MonoBehaviour
{
    public GameObject[] objects;

    private Vector3[] originalpos;

    private void Start()
    {
        originalpos = new Vector3[objects.Length];
        for (int i = 0; i < objects.Length; i++)
        {
            originalpos[i] = objects[i].transform.position;
        }
    }

    private void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, 100))
        {
            if (hit.transform.tag == "Test")
            {
               // if (transform.position.z != originalpos.z - 3)
                 //   StartCoroutine(moveToX(transform, new Vector3(transform.position.x, transform.position.y, transform.position.z - 3), 0.1f));
            }
            else
            {
               // StartCoroutine(moveToX(transform, originalpos, 0.1f));
            }
        }
        else
        {
            // reset
           // StartCoroutine(moveToX(transform, originalpos, 0.1f));
        }
    }

    bool isMoving = false;
    IEnumerator moveToX(Transform fromPosition, Vector3 toPosition, float duration)
    {
        //Make sure there is only one instance of this function running
        if (isMoving)
        {
            yield break; ///exit if this is still running
        }
        isMoving = true;

        float counter = 0;

        //Get the current position of the object to be moved
        Vector3 startPos = fromPosition.position;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);
            yield return null;
        }

        isMoving = false;
    }
}

当 objects 和 originalpos 是单个时,脚本运行良好。 但是现在我把它们做成了数组,因为我有不止一个游戏对象。

我标记了 3 个游戏对象:"Test"、"Test1"、"Test2" 我想对它们执行相同的操作,但对于每个命中的对象。

如果击中 "Test" 仅在 z - 3 上移动 "Test",然后回到原来的位置。 如果点击 "Test1" 仅在 z - 3 上移动 "Test1" 然后返回到它的原始位置。 "Test2".

也一样

做同样的动作,但只针对击中的物体。

您可以使用 Physics.RaycastAll, it returns RaycastHit[] 循环遍历。

像这样:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

RaycastHit[] hits = Physics.RaycastAll(ray, 100f);

// For each object that the raycast hits.
foreach (RaycastHit hit in hits) {

    if (hit.collider.CompareTag("Test")) {
        // Do something.
    } else if (hit.collider.CompareTag("Test1")) {
        // Do something.
    } else if (hit.collider.CompareTag("Test2")) {
        // Do something.
    }
}