Vector3 MyScreenPointToWorldPoint(Vector3 ScreenPoint, Transform target)
{
//得到物体在主相机的某个方向
Vector3 dir = (target.position - Camera.main.transform.position);
//计算投影
Vector3 norVec = Vector3.Project(dir, Camera.main.transform.forward);
return Camera.main.ViewportToWorldPoint(
new Vector3(
ScreenPoint.x/Screen.width,
ScreenPoint.y/Screen.height,
norVec.magnitude
)
);
}
Vector3 startPos;
Vector3 endPos;
Vector3 offset;
private void OnMouseDown() {
startPos = MyScreenPointToWorldPoint(Input.mousePosition, transform);
}
private void OnMouseDrag() {
endPos = MyScreenPointToWorldPoint(Input.mousePosition, transform);
//计算偏移量
offset = endPos - startPos;
//让cube移动
transform.position += offset;
//这一次拖拽的终点变成了下一次拖拽的起点
startPos = endPos;
}
来源:https://www.cnblogs.com/zjp959/p/12214599.html