Unity学习之panel放大缩小和拖拽

首先是拖拽我们的panel

1.打开Unity新建场景,在Hierarchy面板上新建panel。
2.调整锚点如图并更改大小。
如图
3.代码时间,挂在panel上就可以了,点击panel任意位置都可以移动哦。

using UnityEngine;
using UnityEngine.EventSystems;
public class DragUI : MonoBehaviour,IBeginDragHandler,IDragHandler{
   
	Vector3 offset;
	RectTransform rt;
	void Start()
    {
   
        rt = GetComponent<RectTransform>();
    }
    /// <summary>
    /// 开始拖拽
    /// </summary>
    public void OnBeginDrag(PointerEventData eventData)
    {
   
        Vector3 globalMousePos;
        //将屏幕坐标转换为世界坐标
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, null, out globalMousePos))
        {
   
            //计算UI和指针之间的位置偏移量
            offset = rt.position - globalMousePos;
        }
    }
    /// <summary>
    /// 拖拽中
    /// </summary>
    public void OnDrag(PointerEventData eventData)
    {
   
        SetDraggedPosition(eventData);
    }
    private void SetDraggedPosition(PointerEventData eventData)
    {
   
        Vector3 globalMousePos;
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, null, out globalMousePos))
        {
   
            rt.position = offset + globalMousePos;
        }
    }
}

现在我们完成了拖拽的功能,但是没有限制它的一个范围,可能出现拖到game视图外的情况。
4.加入范围

using UnityEngine;
using UnityEngine.EventSystems;   
public class DragUI : MonoBehaviour,IBeginDragHandler,IDragHandler{
   
    Vector3 offset;
    RectTransform rt;  
    float minWidth;//水平最小拖拽范围
    float maxWidth
  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值