2025-07-01 17:54:39 +08:00

123 lines
3.2 KiB
C#

using F3Device.Screen;
using QFramework;
using QFramework.Example;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class UIImageDrag_JiHe : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
RectTransform rect;
Canvas canvas; // 用于坐标转换
List<RaycastResult> raycastResults;
public GameObject target;
//public string targetObjName = uiPanel.Data.TargetObj;
public string targetObjName;
public Vector3 originPos;
bool isOverTarget = false; // 是否在目标物体上结束拖拽
bool isRight = false; // 是否放置正确
void Awake()
{
rect = GetComponent<RectTransform>();
canvas = GetComponentInParent<Canvas>();
originPos = rect.anchoredPosition;
raycastResults = new List<RaycastResult>();
}
// 只有在放置不正确时才允许开始拖拽
public void OnBeginDrag(PointerEventData eventData)
{
if (!isRight)
{
// 确保拖拽时物体在最上层
transform.SetAsLastSibling();
}
else
{
// 阻止事件继续传播
eventData.Use();
}
}
// 只有在放置不正确时才允许拖拽
public void OnDrag(PointerEventData eventData)
{
if (!isRight)
{
rect.transform.position = Input.mousePosition;
}
}
// 只有在放置不正确时才处理拖拽结束事件
public void OnEndDrag(PointerEventData eventData)
{
if (isRight) return;
var uiPanel = UIKit.GetPanel<UIImageSelectMap_JiHe>();
if (uiPanel == null)
{
rect.anchoredPosition = originPos;
return;
}
raycastResults.Clear();
EventSystem.current.RaycastAll(eventData, raycastResults);
target = null;
foreach (var result in raycastResults)
{
if (result.gameObject.name == targetObjName)
{
target = result.gameObject;
break;
}
}
if (target != null)
{
var frame = target.transform.Find("Frame").gameObject;
frame.GetComponent<Image>().color = Color.green;
rect.parent = frame.gameObject.transform;
rect.anchoredPosition =new Vector2(-15, 45);
rect.sizeDelta = new Vector2(176.3376f, 142.2313f);
isRight = true;
Debug.Log("放置正确,禁用拖拽");
// 禁用射线检测,防止再次被拖拽
GraphicRaycaster graphicRaycaster = GetComponent<GraphicRaycaster>();
if (graphicRaycaster != null)
{
graphicRaycaster.enabled = false;
}
// 或者禁用Image组件的raycastTarget
Image image = GetComponent<Image>();
if (image != null)
{
image.raycastTarget = false;
}
// 通知UI面板操作成功
// uiPanel.OnDragSuccess();
}
else
{
rect.anchoredPosition = originPos;
LayoutRebuilder.ForceRebuildLayoutImmediate(rect.transform.parent.GetComponent<RectTransform>());
}
isOverTarget = false;
target = null;
}
}