UGUI 拖拽范围检测

 

ugui 的拖拽在游戏中经常用到,只要继承相关接口并实现就能完成. 并且我这个是加了范围检测的,希望能帮到你!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class DragCheck : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler

{
    public bool _isCheckZone = false;

    // Use this for initialization
    void Start ()
    {
		
	}
	
	// Update is called once per frame
	void Update ()
    {
		
	}

    // begin dragging
    public void OnBeginDrag(PointerEventData eventData)
    {
        SetDraggedPosition(eventData);
    }

    // during dragging
    public void OnDrag(PointerEventData eventData)
    {
        SetDraggedPosition(eventData);
    }

    // end dragging
    public void OnEndDrag(PointerEventData eventData)
    {
        SetDraggedPosition(eventData);
    }

    /// <summary>
    /// set position of the dragged game object
    /// </summary>
    /// <param name="eventData"></param>
    private void SetDraggedPosition(PointerEventData eventData)
    {
        var rt = gameObject.GetComponent<RectTransform>();

        // transform the screen point to world point int rectangle
        Vector3 globalMousePos;
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, eventData.pressEventCamera, out globalMousePos))
        {
            float x = globalMousePos.x, y = globalMousePos.y;
            Debug.Log("x:" +x +"y:" +y);
            rt.position = _isCheckZone ? CheckPos(x,y) : new Vector2(x,y);
        }
    }


    Vector2 CheckPos(float x, float y)
    {
        if (x < 120)
            x = 120;
        else if (x > 600)
            x = 600;
        if (y > 920)
            y = 920;
        else if (y < 320)
            y = 320;
        return new Vector2(x, y);
    }

}

如果限制范围,就不会出框,至于范围边界,自己用的时候设置一下就行了.
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值