Unity UGUI实现鼠标拖动图片

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

// UGUI拖动图片,脚本挂在Image上即可
public class TuoDongWuPin : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
    
    private Image img;//实例化后的对象
    Vector3 offPos;//存储按下鼠标时的图片-鼠标位置差
    Vector3 arragedPos; //保存经过整理后的向量,用于图片移动
    /// <summary>
    /// 开始拖拽的时候
    /// </summary>
    /// <param name="eventData"></param>
    public void OnBeginDrag(PointerEventData eventData)
    {
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(transform.GetComponent<RectTransform>(), Input.mousePosition
     , eventData.enterEventCamera, out arragedPos))
        {
            offPos = transform.position - arragedPos;
        }
    }
    /// <summary>
    /// 拖拽中
    /// </summary>
    /// <param name="eventData"></param>
    public void OnDrag(PointerEventData eventData)
    {
        transform.position = offPos + Input.mousePosition;
    }
    /// <summary>
    /// 拖拽结束,图片停留在结束位置
    /// </summary>
    /// <param name="eventData"></param>
    public void OnEndDrag(PointerEventData eventData)
    {
        transform.position = offPos + Input.mousePosition;
    }
}
  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值