知识点
- 向量
- 射线检测
- 坐标转换
思路
- 使用射线检测获取射线检测点与模型对象之间的偏移量 (世界空间)
- 使用相机的坐标转换获取检测点与鼠标位置之间的偏移量 (屏幕空间)
- 拖拽时,更新模型位置
代码示例
using UnityEngine;
public class TestDrag : MonoBehaviour
{
public Vector3 worldSpaceOffest;
public Vector3 screenSpaceOffest;
public Vector3 hitPointInScreenSpacePos;
public Vector3 hitPoinitInWorldSpacePos;
RaycastHit hit;
private void OnMouseDown()
{
Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100f);
worldSpaceOffest = transform.position - hit.point;
screenSpaceOffest = Camera.main.WorldToScreenPoint(hit.point) - Input.mousePosition;
}
private void OnMouseDrag()
{
hitPointInScreenSpacePos = Input.mousePosition + screenSpaceOffest;
hitPoinitInWorldSpacePos = Camera.main.ScreenToWorldPoint(hitPointInScreenSpacePos);
transform.position = hitPoinitInWorldSpacePos + worldSpaceOffest;
}
}