1. 程式人生 > >unity3D點選觸發攝像機發出射線

unity3D點選觸發攝像機發出射線

   if (Input.GetMouseButton(0))
        {
            Debug.Log("xxxxxxxxxxxxxxxxxxxxxx");

            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//從攝像機發出到點選座標的射線
            RaycastHit hitInfo;
            if (Physics.Raycast(ray, out hitInfo))
            {
                Debug.DrawLine(ray.origin, hitInfo.point);//劃出射線,在scene檢視中能看到由攝像機發射出的射線
                GameObject gameObj = hitInfo.collider.gameObject;
                if (gameObj.name.StartsWith("Cube") == true)//當射線碰撞目標的name包含Cube,執行拾取操作
                {
                    Debug.Log(gameObj.name);
                }
            }
        }