unity中图片实行拖拽功能

将脚本拖到需要实现拖拽功能的UI图片上即可话不多说直接上代码using System;using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.EventSystems;public class UIDragByMocha : MonoBehaviour,...
摘要由CSDN通过智能技术生成

将脚本拖到需要实现拖拽功能的UI图片上即可
话不多说直接上代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class UIDragByMocha : MonoBehaviour, IBeginDragHandler, IDragHandler,      IEndDragHandler
{

[Header("是否精准拖拽")]
public bool m_isPrecision;

//存储图片中心点与鼠标点击点的偏移量
private Vector3 m_offset;

//存储当前拖拽图片的RectTransform组件
private RectTransform m_rt;

void Start()
{
    //初始化
    m_rt = gameObject.GetComponent<RectTransform>();
}

//开始拖拽触发
public void OnBeginDrag(PointerEventData eventData)
{
    //如果精准拖拽则进行计算偏移量操作
    if(m_isPrecision)
    {
        //存储点击时的鼠标坐标
        Vector3 tWorldPos;
        //UI屏幕坐标转换为世界坐标
        RectTransformUtility.ScreenPointToWorldPointInRectangle(m_rt, eventData.position, eventData.pressEventCamera, out tWorldPos);
        //计算偏移量
        m_offset = transform.position - tWorldPos;
    }
    //否则 默认偏移量为0
    else
    {
        m
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值