89 lines
2.4 KiB
C#
89 lines
2.4 KiB
C#
using DG.Tweening;
|
|
using QFramework;
|
|
using System;
|
|
using UnityEngine;
|
|
using UnityEngine.Events;
|
|
|
|
public class ObjDrag : MonoBehaviour
|
|
{
|
|
private Vector3 offset;
|
|
public bool isOn = false;
|
|
|
|
Vector3 startPosition;
|
|
|
|
public UnityEvent<GameObject> OnDragEnd = new UnityEvent<GameObject>();
|
|
void Start()
|
|
{
|
|
startPosition = gameObject.transform.position;
|
|
}
|
|
|
|
private void OnMouseUp()
|
|
{
|
|
if (isOn)
|
|
{
|
|
Show3DCamera.instance.lockMove = false;
|
|
OnDragEnd?.Invoke(gameObject);
|
|
}
|
|
}
|
|
|
|
void OnMouseDown()
|
|
{
|
|
if (isOn)
|
|
{
|
|
// 获取鼠标在相机视角平面上的世界坐标
|
|
Vector3 mouseWorldPos = GetMouseWorldPositionOnPlane();
|
|
// 计算物体位置与鼠标点击点在世界坐标中的偏移量
|
|
offset = transform.position - mouseWorldPos;
|
|
Show3DCamera.instance.lockMove = true;
|
|
}
|
|
}
|
|
|
|
void OnMouseDrag()
|
|
{
|
|
if (isOn)
|
|
{
|
|
// 获取鼠标在相机视角平面上的世界坐标
|
|
Vector3 mouseWorldPos = GetMouseWorldPositionOnPlane();
|
|
// 根据偏移量更新物体的位置
|
|
transform.position = mouseWorldPos + offset;
|
|
}
|
|
}
|
|
|
|
private Vector3 GetMouseWorldPositionOnPlane()
|
|
{
|
|
// 获取鼠标在屏幕上的位置
|
|
Vector3 mouseScreenPos = Input.mousePosition;
|
|
mouseScreenPos.z = Camera.main.WorldToScreenPoint(transform.position).z; // 保持物体与相机的深度一致
|
|
|
|
// 将鼠标的屏幕坐标转换为世界坐标
|
|
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(mouseScreenPos);
|
|
|
|
// 计算相机视角平面的法线方向(相机的正前方)
|
|
Vector3 cameraForward = Camera.main.transform.forward;
|
|
|
|
// 创建一个平面,法线方向为相机的正前方,平面通过物体的当前位置
|
|
Plane plane = new Plane(cameraForward, transform.position);
|
|
|
|
// 从相机发射一条射线,指向鼠标的世界坐标
|
|
Ray ray = Camera.main.ScreenPointToRay(mouseScreenPos);
|
|
|
|
float distance;
|
|
if (plane.Raycast(ray, out distance))
|
|
{
|
|
// 返回射线与平面的交点
|
|
return ray.GetPoint(distance);
|
|
}
|
|
|
|
// 如果没有相交,返回物体的当前位置
|
|
return transform.position;
|
|
}
|
|
|
|
// 双击事件处理函数
|
|
public void OnDoubleClick()
|
|
{
|
|
// 在这里可以添加你想要执行的双击逻辑
|
|
// 例如,将物体重置到起始位置
|
|
//transform.position = startPosition;
|
|
transform.DOMove(startPosition, 0.1f);
|
|
}
|
|
} |