VirtualFramework/Assets/Scripts/UI/UIBody3DMouse.cs
2025-03-11 10:33:07 +08:00

137 lines
4.2 KiB
C#

using UnityEngine;
using UnityEngine.UI;
using QFramework;
using System;
namespace QFramework.Example
{
public class UIBody3DMouseData : UIPanelData
{
}
public partial class UIBody3DMouse : UIPanel
{
UIDragItem dragItem;
private GameObject currentHitObject; // 当前被击中的物体
private bool isObjectHit; // 标记是否有物体被击中
protected override void OnInit(IUIData uiData = null)
{
TypeEventSystem.Global.Register<OnModuleQuit>(OnModuleQuithandler).UnRegisterWhenGameObjectDestroyed(this);
mData = uiData as UIBody3DMouseData ?? new UIBody3DMouseData();
dragItem = Content.GetComponent<UIDragItem>();
SelectBtn.onClick.AddListener(() =>
{
if (currentHitObject != null)
{
var item = currentHitObject.GetComponent<Body3DOjbItem>();
if (item != null)
{
item.objToggle.OnValueChanged.Invoke(!item.objToggle.isOn);
}
}
});
}
private void OnModuleQuithandler(OnModuleQuit quit)
{
Hide();
}
private void OnEndDrag()
{
Show3DCamera.instance.lockMove = false;
}
private void OnBeginDrag()
{
Show3DCamera.instance.lockMove = true;
}
protected override void OnOpen(IUIData uiData = null)
{
dragItem?.OnBeginDragEvent.AddListener(OnBeginDrag);
dragItem?.OnEndDragEvent.AddListener(OnEndDrag);
}
private void Update()
{
if (Point != null && Camera.main != null)
{
// 获取 Image 组件的中心点屏幕坐标
Vector2 imageCenter = new Vector2(Point.rectTransform.position.x, Point.rectTransform.position.y);
// 将屏幕坐标转换为射线
Ray ray = Camera.main.ScreenPointToRay(imageCenter);
RaycastHit hit;
// 进行射线检测
if (Physics.Raycast(ray, out hit))
{
GameObject hitObject = hit.collider.gameObject;
if (!isObjectHit)
{
// 射线首次进入物体
currentHitObject = hitObject;
isObjectHit = true;
Debug.Log("射线进入物体: " + hitObject.name);
OnEnterBody(currentHitObject);
}
else if (currentHitObject != hitObject)
{
// 射线从之前的物体移除并击中了新物体
Debug.Log("射线移除物体: " + currentHitObject.name);
OnExitBody(currentHitObject);
currentHitObject = hitObject;
OnEnterBody(currentHitObject);
Debug.Log("射线进入物体: " + hitObject.name);
}
}
else
{
if (isObjectHit)
{
// 射线移除当前物体
OnExitBody(currentHitObject);
Debug.Log("射线移除物体: " + currentHitObject.name);
currentHitObject = null;
isObjectHit = false;
}
}
}
}
void OnEnterBody(GameObject obj)
{
if (obj != null)
{
var bodyItem = currentHitObject.GetComponent<Body3DOjbItem>();
if (bodyItem != null)
{
BodyName.text = bodyItem.body.Name;
BodyName.gameObject.SetActive(true);
}
}
}
void OnExitBody(GameObject obj)
{
BodyName.gameObject.SetActive(false);
}
protected override void OnShow()
{
}
protected override void OnHide()
{
dragItem?.OnBeginDragEvent.RemoveListener(OnBeginDrag);
dragItem?.OnEndDragEvent.RemoveListener(OnEndDrag);
}
protected override void OnClose()
{
}
}
}