首页 > 代码库 > camera.ScreenPointToRay(),camera.ScreenToWorldPoint()与Raycast()

camera.ScreenPointToRay(),camera.ScreenToWorldPoint()与Raycast()

  1. camera.ScreenPointToRay(Input.mousePosition),自camera.tranform.position起经过Input.mousePosition发射一条ray并返回ray
  2. camera.ScreenToWorldPoint(Input.mousePosition+new Vector3(0, 0, (xxx))),将屏幕坐标转换为世界坐标,但必须赋z值,z值应为摄像机到该点所在平面的投影
  3. 不要忘记distance参数,使用layermask可能与distance混淆
  4.  1 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);                2             RaycastHit hit; 3  4             if (Physics.Raycast(ray,out hit,layermask)) 5             { 6                 Vector3 dir = hit.point - Camera.main.transform.position;                   //dir为由摄像机指向摄像机到射线打到的点的向量 7                 Vector3 forward = Camera.main.transform.forward;                            //指向摄像机正前方的单位向量 8                 Debug.Log("Camera.main.ScreenToWorldPoint(Input.mousePosition) "  9                     + Camera.main.ScreenToWorldPoint(Input.mousePosition)10                     + new Vector3(0, 0, (Vector3.Dot(dir, forward))));                      //Vector3.Dot(dir, forward)为dir与forward的点乘,几何意义为dir在forward上的投影11                 Debug.Log("hit.point " + hit.point);12             }
    View Code

    

 

camera.ScreenPointToRay(),camera.ScreenToWorldPoint()与Raycast()