79 lines
2.2 KiB
C#
79 lines
2.2 KiB
C#
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.EventSystems;
|
|
using UnityEngine.UI;
|
|
|
|
public class ToolDragSpawner : MonoBehaviour,
|
|
IPointerDownHandler, IDragHandler, IPointerUpHandler
|
|
{
|
|
public GameObject dragGhostPrefab;
|
|
public Transform dragLayer;
|
|
|
|
private GameObject ghost;
|
|
private RectTransform ghostRect;
|
|
|
|
private RectTransform selfRect;
|
|
|
|
public void OnPointerDown(PointerEventData eventData)
|
|
{
|
|
// 创建影子
|
|
ghost = Instantiate(dragGhostPrefab, dragLayer);
|
|
|
|
// 同步图片
|
|
Image src = GetComponent<Image>();
|
|
Image dst = ghost.GetComponent<Image>();
|
|
ghostRect = ghost.transform as RectTransform;
|
|
selfRect=transform.GetComponent<RectTransform>();
|
|
dst.sprite = src.sprite;
|
|
SyncRectTransform(selfRect, ghostRect);
|
|
ghost.transform.position = eventData.position;
|
|
}
|
|
|
|
public void OnDrag(PointerEventData eventData)
|
|
{
|
|
if (ghost != null)
|
|
ghost.transform.position = eventData.position;
|
|
}
|
|
|
|
public void OnPointerUp(PointerEventData eventData)
|
|
{
|
|
// 抬起事件(重点)
|
|
HandleDrop(eventData);
|
|
|
|
Destroy(ghost);
|
|
}
|
|
|
|
void SyncRectTransform(RectTransform src, RectTransform dst)
|
|
{
|
|
dst.anchorMin = src.anchorMin;
|
|
dst.anchorMax = src.anchorMax;
|
|
dst.pivot = src.pivot;
|
|
dst.sizeDelta = src.sizeDelta;
|
|
dst.localScale = Vector3.one; // 防止父节点缩放干扰
|
|
}
|
|
|
|
void HandleDrop(PointerEventData eventData)
|
|
{
|
|
// UI 命中检测
|
|
if (IsClickUI())
|
|
{
|
|
Debug.Log("在UI上抬起");
|
|
}
|
|
else
|
|
{
|
|
Debug.Log("拖拽到非UI区域");
|
|
// 👉 在这里生成3D模型
|
|
}
|
|
}
|
|
|
|
private bool IsClickUI()
|
|
{
|
|
PointerEventData eventData = new PointerEventData(EventSystem.current);
|
|
eventData.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
|
|
List<RaycastResult> raycastResults = new List<RaycastResult>();
|
|
EventSystem.current.RaycastAll(eventData, raycastResults);
|
|
|
|
return raycastResults.Count > 0;
|
|
}
|
|
}
|