unity 射线检测(简易版)

void Update () {
        if (Input.GetMouseButton(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//从摄像机上鼠标的位置取得一条射线
            RaycastHit hitInfo;
            //Debug.DrawRay(ray.origin, ray.direction, Color.red);
            //画条红条以便观察
            Debug.DrawLine(ray.origin, ray.origin + (ray.direction * 100), Color.red);
            if (Physics.Raycast(ray, out hitInfo, 100))  //检测到东西则返回true
            {
                GameObject gameObj = hitInfo.collider.gameObject;
                if (gameObj != null)
                {
                    print("onColission:" + gameObj.name);
                }
            }
        }
}

 1. 注意DrawLine 和 DrawRay的区别

2. 检测到的东西信息保存在·hitInfo·中

3.被检测的东西需要有collider组件。

猜你喜欢

转载自blog.csdn.net/u013749051/article/details/83715532