1、当相机是正交(orthogonalic)相机
public class BollardTest : MonoBehaviour
{
void Update()
{
if(Input.GetMouseButton(0))
{
Vector3 pos = WorldTouchPos();
Debug.Log("点击-世界位置" + pos);
}
}
public Vector3 WorldTouchPos()
{
return Camera.main.ScreenToWorldPoint(GetTouchPosition());
}
public static Vector3 GetTouchPosition()
{
#if UNITY_EDITOR || UNITY_STANDALONE_WIN
return Input.mousePosition;
#else
return Input.touches[0].position;
#endif
}
}
2、当相机是透视(Perspective)相机
public class BollardTest : MonoBehaviour
{
void Update()
{
if(Input.GetMouseButton(0))
{
Vector3 pos = WorldTouchPos();
Debug.Log("点击-世界位置" + pos);
}
}
public Vector3 WorldTouchPos()
{
Ray ray = m_camera.ScreenPointToRay(GetTouchPosition());//射线检测碰撞到的第一个物体
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
return hit.point;
}
}
public static Vector3 GetTouchPosition()
{
#if UNITY_EDITOR || UNITY_STANDALONE_WIN
return Input.mousePosition;
#else
return Input.touches[0].position;
#endif
}
}