74 lines
2.3 KiB
C#

using UnityEngine;
using UnityEngine.EventSystems;
using ZXKFramework;
public class MouseDragObj : MonoBehaviour
{
private Vector3 screenPoint;
private Vector3 offset;
private Camera mCamera;
[HideInInspector]
public bool isDrag;
public float distance = 1f;
public bool lookat;
private void OnMouseDown()
{
if (EventSystem.current && EventSystem.current.IsPointerOverGameObject()) return;
isDrag = true;
if (!mCamera)
{
mCamera = Camera.main;
}
screenPoint = mCamera.WorldToScreenPoint(transform.position);
offset = transform.position - mCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
//位置复原
private void OnMouseUp()
{
isDrag = false;
if(TryGetComponent(out ResetPosRot reset))
{
reset.ResetGameObject();
}
}
private void OnMouseDrag()
{
if (isDrag && Input.GetMouseButton(0))
{
Ray ray = mCamera.ScreenPointToRay(Input.mousePosition); // 将鼠标位置转换为射线
transform.position = ray.GetPoint(distance) + offset;
if(lookat) { transform.LookAt(mCamera.transform); }
if (TryGetComponent(out PC_DragEvent dragEvent))
{
dragEvent.stay?.Invoke(gameObject);
}
RaycastHit[] hits = Physics.RaycastAll(ray); // 进行射线检测并返回所有命中结果数组
foreach (var hit in hits) // 遍历每个命中结果
{
if (hit.transform.TryGetComponent(out PC_TriggerEvent triggerEvent))
{
if (triggerEvent.trigger != null)
{
triggerEvent.trigger.Invoke(gameObject);
}
else
{
if (TryGetComponent(out PC_TriggerEvent triggerEvent_))
{
triggerEvent_.trigger?.Invoke(hit.transform.gameObject);
}
}
}
}
}
}
private void OnDisable()
{
isDrag = false;
if (TryGetComponent(out ResetPosRot reset))
{
reset.ResetGameObject();
}
}
}