Unity中拖动的简单实现(UGUI以及3D物体)

拖动的基本代码如下

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

[RequireComponent(typeof( RectTransform))]
public class UGUIDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    private bool isDrag = false;
    //偏移量
    private Vector3 offset = Vector3.zero;

    public void OnBeginDrag(PointerEventData eventData)
    {
        isDrag = false;
        SetDragObjPostion(eventData);
    }

    public void OnDrag(PointerEventData eventData)
    {
        isDrag = true;
        SetDragObjPostion(eventData); 
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        SetDragObjPostion(eventData);
    }



    void SetDragObjPostion(PointerEventData eventData)
    {
        RectTransform rect = this.GetComponent<RectTransform>();
        Vector3 mouseWorldPosition;

        //判断是否点到UI图片上的时候
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rect, eventData.position, eventData.pressEventCamera, out mouseWorldPosition))
        {
            if (isDrag)
            {
                rect.position = mouseWorldPosition + offset;
            }
            else
            { 
	           //计算偏移量
                offset = rect.position - mouseWorldPosition;
            }

            //直接赋予position点到的时候回跳动
            //rect.position = mouseWorldPosition;
        }
    }
}

UGUI中

只需要将上面的代码拖到想要移动的物体上即可
场景中需要一个EventSystem,一般创建UGUI的时候会自动生成


3D物体上

需要在摄像机上加入 Physics RayCaster 组件
另外物体上需要有Collider
场景中需要一个EventSystem
将上面脚本拖到需要拖动的物体对象上即可


扩展:其实我们可以继承许多的接口,参考上面的方法可以实现许多我么需要的效果。包括点击等等。
这里写图片描述

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值