Unity3D Image 拖拽

Unity3D 一句话代码实现UGUI图片的拖拽功能

在本文,你将学会如何使用一句话代码实现UGUI图片的拖动,不需要坐标的转换,不需要Piovt的变换

效果演示:

 

效果演示


Tips: Showinfo脚本仅仅是为了看到笔者鼠标是否进行着触发而添加的,别无它用

 

代码:

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class movePic : MonoBehaviour,IDragHandler ,IPointerDownHandler{
    private RawImage img; 
    Vector3 offsetPos; //存储按下鼠标时的图片-鼠标位置差
    void Start()
    {
        img = GetComponent<RawImage>();//获取图片,因为我们要获取他的RectTransform
    }
    public void OnDrag(PointerEventData eventData)
    {
        //将鼠标的位置坐标进行钳制,然后加上位置差再赋值给图片position
        img.rectTransform.position = new Vector3(Mathf.Clamp(Input.mousePosition.x, 0, Screen.width), Mathf.Clamp(Input.mousePosition.y, 0, Screen.height), 0) + offsetPos;
    }
    public void OnPointerDown(PointerEventData eventData)
    {
        offsetPos = img.rectTransform.position - Input.mousePosition;
    }
}

Tips:

  1. 最简代码,不涉及到Rect坐标转换,不考虑Piovt;
  2. 需要using UnityEngine.EventSystem
  3. 继承2个接口IDragHandlerIPointerDownHandler,在接口的实现中加入图片移动逻辑

简单拓展

可以作为输入框背景,输入框既美观又实用

特别关注

上述代码实现的前提是:Canvas -RenderMode-ScreenSpace_Overlay
如果要实现:Canvas -RenderMode-Word Space下的图片拖拽,涉及到坐标装换,也是挺简单:

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

public class MoveImage : MonoBehaviour, IDragHandler, IPointerDownHandler
{
    private Image img;
    Vector3 offsetPos; //存储按下鼠标时的图片-鼠标位置差
    Vector3 arragedPos; //保存经过整理后的向量,用于图片移动
    void Start()
    {
        img = GetComponent<Image>();//获取图片,因为我们要获取他的RectTransform
    }
    public void OnDrag(PointerEventData eventData)
    {
        //将鼠标的位置坐标进行钳制,然后加上位置差再赋值给图片position
        img.transform.position =Camera.main.ScreenToWorldPoint(new Vector3(Mathf.Clamp(Input.mousePosition.x, 0, Screen.width), Mathf.Clamp(Input.mousePosition.y, 0, Screen.height), 0) + offsetPos);
    }
    public void OnPointerDown(PointerEventData eventData)
    {
        offsetPos = Camera.main.WorldToScreenPoint(img.rectTransform.position) - Input.mousePosition;
    }
}

Tips:请注意我用到了:Camera.main.WorldToScreenPointCamera.main.ScreenToWorldPoint

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值