首页 > 代码库 > 【Unity笔记】经典的鼠标点击射线检测碰撞

【Unity笔记】经典的鼠标点击射线检测碰撞

void Update (){
    if(Input.GetMouseButton(0)){
        //从摄像机发出到点击坐标的射线
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;
        if(Physics.Raycast(ray,out hitInfo)){
            //划出射线,只有在scene视图中才能看到
            Debug.DrawLine(ray.origin,hitInfo.point);
            GameObject gameObj = hitInfo.collider.gameObject;
            Debug.Log("click object name is " + gameObj.name);
            //当射线碰撞目标为boot类型的物品,执行拾取操作
            if(gameObj.tag == "boot"){
                Debug.Log("pickup!");
            }
        }
    }
}

 

【Unity笔记】经典的鼠标点击射线检测碰撞