UGUI拖拽事件的实现

UGUI 自带有拖拽事件,我们具体来实现看看,为了便于理解,我尽量去除不必要的代码.

第一步:继承3个接口:IBeginDragHandler,IDragHandler,IEndDragHandler,分别是拖拽开始,拖拽途中,拖拽结束.(实现相应方法)

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class NeedMountScript : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler{


    public void OnBeginDrag(PointerEventData eventData){

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

        Debug.Log(eventData.position);
    }
    public void OnEndDrag(PointerEventData eventData){
        Debug.Log("结束拖拽");

    }
}

我们打印出 eventData.position,可以明白这个坐标就是屏幕坐标,左下角起始点(0,0)
第二步:让 ui 跟随鼠标移动.

只需要3句话:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class NeedMountScript : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler{


    public void OnBeginDrag(PointerEventData eventData){

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

        Vector3 pos;
        RectTransformUtility.ScreenPointToWorldPointInRectangle(GetComponent<Image>().rectTransform,eventData.position,eventData.pressEventCamera,out pos);

        transform.position = pos;

    }
    public void OnEndDrag(PointerEventData eventData){
        Debug.Log("结束拖拽");

    }
}

拖拽的时候不停更新 eventData.position 的位置,把他转成世界坐标,不停赋值给图片的 position 就行了,看看实际效果吧!

这里写图片描述

ps:不要忘了把脚本挂在 ui 上面额,既然实现了拖拽,那么下一篇就来实现虚拟摇杆吧.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值