unity 鼠标拖拽ui

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class DrapAndDrop : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{

    private RectTransform rectTransform;
    /// <summary>
    /// 判断碰撞是否正确
    /// </summary>
    public bool isRight;
    /// <summary>
    /// 碰撞物体的名字
    /// </summary>
    private string CollisionName;
    /// <summary>
    /// 判断物体的坐标
    /// </summary>
    private Vector3 collisionPos;
    /// <summary>
    ///是否拖拽
    /// </summary>
    private bool isDrage;

 

    void Start()
    {
        rectTransform = GetComponent<RectTransform>();
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        //Debug.Log("开始拖拽");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 pos;
        RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, eventData.position, eventData.enterEventCamera, out pos);
        rectTransform.position = pos;
        isDrage = true;
    }


    public void OnEndDrag(PointerEventData eventData)
    {
        //Debug.Log("物体名字:" + CollisionName);
        isDrage = false;
    }

 

    private void OnTriggerStay2D(Collider2D collision)
    {
        //print("被碰撞物体是:" + collision.name);
        CollisionName = collision.name;
        collisionPos = collision.transform.localPosition;
        Panduan();
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        isRight = false;
        CollisionName = null;
    }


    /// <summary>
    /// 正确与否判断
    /// </summary>
    private  void Panduan()
    {
        //没有停止拖拽不进行判断
        if (isDrage) return;
        //进行判断
        if (CollisionName.Substring(0, 1) == "q")
        {
            int dragNumber = int.Parse(this.gameObject.name.Substring(1));
            int collisionNumber = int.Parse(CollisionName.Substring(1));

            this.gameObject.transform.localPosition = collisionPos;
            //数字相同,就是判断正确
            if (dragNumber == collisionNumber)
            {
                isRight = true;
            }
            else
            {
                isRight = false;
            }

        }
        else
        {
            //print("碰到其他物体");
            isRight = false;
            CollisionName = null;
        }

    }

 

 

}

 

发布了68 篇原创文章 · 获赞 11 · 访问量 3万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览