unity 射线检测总结

后面继续研究,关于layer分层检测的问题,有点头疼,有时间要继续刚

1.射线普通检测,如果 Ray 跟系统命名冲突,只需要在前面加上 UnityEngine. 就行了

  UnityEngine.Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray,out hit))
        {
            if (hit.collider.gameObject.name == "Cube" )
            {
                print("你检测到了一个 Cube");
            }
        }

2.射线检测多个物体

   UnityEngine.Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit[] hits = Physics.RaycastAll(ray);
        if (hits.Length > 0)
        {
            foreach (var item in hits)
            {
                print(item.collider.gameObject.name);
            }
        }

3.射线分层检测,丫的,这个只有第一个 bool 是成立的,能够实现分层检测,其他两个就是不能,有人知道的话告诉我 ,万分感激(丫的,同样的代码,晚上一试就都行了,我真的是日狗了)还有一个问题就是第三个 bool 从摄像机到 鼠标点画线不知道为什么方向是错的

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

public class Ray : MonoBehaviour {

    public Transform cam;
    public Transform cube;
   // Update is called once per frame
 void Update () {
        UnityEngine.Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        LayerMask mask =1 << LayerMask.NameToLayer("layer");
        RaycastHit hit;

        // bool grounded = Physics.Raycast(cam.position, transform.forward, out hit, 10000f, 1 << LayerMask.NameToLayer("layer"));
        bool grounded = Physics.Raycast(ray, out hit,10000f, mask.value);
       //  bool grounded = Physics.Raycast(cam.position,cam.position - Input.mousePosition, out hit,10000f, 1 << LayerMask.NameToLayer("layer"));

        Debug.DrawRay(ray.origin,ray.direction* 10000f, Color.red);
        if (grounded)
        {
            if (hit.collider.CompareTag("layer"))
            {
                Debug.LogError("发生了碰撞");
                Debug.LogError("距离是:" + hit.distance);
                Debug.LogError("被碰撞的物体是:" + hit.collider.gameObject.name);
            }else
            {
                Debug.LogError("This layer no this tag!");
            }

        }
        else
        {
            Debug.LogError("碰撞结束");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39097425/article/details/83718491