视频效果:
工程网盘链接:
链接:https://pan.baidu.com/s/1atvfKceU1PnPPUE4mCEseg
提取码:1212
关键代码:
/// <summary>
/// 鼠标按下
/// </summary>
private Vector3 offset;
private void OnMouseDown()
{
isDrag = true;
SetSelectView();
//根据模型坐标系确定移动方向
moveDir = transform.up;
startPos = operaObj.transform.position;
//保存上一次位置 不要Z值
lastPos = (Vector2)Input.mousePosition;
}
private Vector3 axisPos;
private Vector3 worldPos;
//上一次鼠标点位 (屏幕坐标)
private Vector3 lastPos;
private void OnMouseDrag()
{
//当前鼠标位置 不要Z值
axisPos = (Vector2)Input.mousePosition;
//计算轴的屏幕坐标下的方向
Vector3 moveDir2D = (Camera.main.WorldToScreenPoint(startPos + moveDir) - Camera.main.WorldToScreenPoint(startPos)).normalized;
//鼠标移动方向 包括方向
Vector3 dir = axisPos - lastPos;
//将鼠标移动方向投影到轴
dir = Vector3.Dot(dir, moveDir2D) * moveDir2D;
//通过位置+方向 得到这一帧移动到的位置(屏幕坐标)
Vector3 point2D = Camera.main.WorldToScreenPoint(operaObj.transform.position) + dir;
//将该移动到的(屏幕)点转成(世界)点
worldPos = Camera.main.ScreenToWorldPoint(point2D);
worldPos = startPos + Vector3.Dot(worldPos - startPos, moveDir) * moveDir;
operaObj.transform.position = worldPos;
//保存上一次位置 不要Z值
lastPos = (Vector2)Input.mousePosition;
}
/// <summary>
/// 鼠标抬起
/// </summary>
private void OnMouseUp()
{
isDrag = false;
SetNoSelectView();
}