70 lines
2.0 KiB
C#
70 lines
2.0 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.EventSystems;
|
|
using UnityEngine.UI;
|
|
|
|
public class cardcaozuo : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler
|
|
{
|
|
[Header("给一个canvas")]
|
|
public Canvas canvas;
|
|
[Header("显示的image")]
|
|
public Image cardIconImage;
|
|
[Header("对应的sprite")]
|
|
public Sprite cardicon;
|
|
[Header("目标点的名字")]
|
|
public string targetTag;
|
|
private Transform recordParent;//记录父节点
|
|
private SpriteAniation spriteAniation;
|
|
// Start is called before the first frame update
|
|
void Start()
|
|
{
|
|
this.cardIconImage.sprite = cardicon;
|
|
spriteAniation = GetComponent<SpriteAniation>();
|
|
spriteAniation.enabled = false;
|
|
}
|
|
|
|
// 拖拽开始
|
|
public void OnBeginDrag(PointerEventData eventData)
|
|
{
|
|
|
|
this.recordParent = this.transform.parent;
|
|
|
|
this.transform.SetParent(canvas.transform);
|
|
//throw new System.NotImplementedException();
|
|
}
|
|
// 拖拽中
|
|
public void OnDrag(PointerEventData eventData)
|
|
{
|
|
this.transform.position = Input.mousePosition;
|
|
}
|
|
// 拖拽结束
|
|
public void OnEndDrag(PointerEventData eventData)
|
|
{
|
|
// 检测鼠标下的目标
|
|
List<RaycastResult> results = new List<RaycastResult>();
|
|
EventSystem.current.RaycastAll(eventData, results);
|
|
|
|
foreach (var result in results)
|
|
{
|
|
if (result.gameObject.CompareTag(targetTag)) // 检测目标是否为目标点
|
|
{
|
|
Debug.Log("成功放置到目标区域!");
|
|
transform.SetParent(result.gameObject.transform); // 设置为目标点的子物体
|
|
transform.localPosition = Vector3.zero; // 重置位置
|
|
this.enabled = false;//禁用自己
|
|
|
|
spriteAniation.enabled = true;
|
|
return;
|
|
}
|
|
}
|
|
|
|
// 如果不在目标区域,返回原始父节点
|
|
Debug.Log("未放置到目标区域,返回原位置");
|
|
transform.SetParent(recordParent);
|
|
transform.localPosition = Vector3.zero; // 重置到原始位置
|
|
}
|
|
}
|
|
|
|
|