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
}
}
本文对比了Unity中正交相机与透视相机下,如何通过Input获取触屏位置并转换为世界坐标的过程。正交相机使用ScreenToWorldPoint,透视相机则借助Raycasting检测碰撞。
865

被折叠的 条评论
为什么被折叠?



