美文网首页unity3D技术分享Unity教程合集
unity3d 简单拖拽交换对象,类似背包物品交换功能

unity3d 简单拖拽交换对象,类似背包物品交换功能

作者: 好怕怕 | 来源:发表于2017-03-09 17:53 被阅读644次

直接挂载到需要拖拽的每个对象上就可以了

图片.png
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class OnTestDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    private Vector3 beginPos;
    private Image image;
    void Start()
    {
        beginPos = transform.position;
        image = transform.GetComponent<Image>();
    }
    public void OnBeginDrag(PointerEventData eventData)
    {
        image.raycastTarget = false;
        beginPos = transform.position;
        transform.SetAsLastSibling();
   }

    public void OnDrag(PointerEventData eventData)
    {
        transform.position = Input.mousePosition;
        transform.localScale = new Vector3(0.8f, 0.8f, 0.8f);
        OnTestDrag drag = eventData.pointerEnter.GetComponent<OnTestDrag>();
        if (drag != null && drag.transform != transform)
        {
            transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        OnTestDrag drag = eventData.pointerEnter.GetComponent<OnTestDrag>();
        if (drag != null && drag.transform != transform)
        {
            Vector3 pos = drag.transform.position;
            drag.transform.position = beginPos;
            transform.position = pos;
            transform.localScale = Vector3.one;
        }
        else
        {
            transform.position = beginPos;
            transform.localScale = Vector3.one;

        }
        image.raycastTarget = true;
    }

}

相关文章

网友评论

    本文标题:unity3d 简单拖拽交换对象,类似背包物品交换功能

    本文链接:https://www.haomeiwen.com/subject/bkhggttx.html