Unity 实现物体拖拽
Unity实现拖拽可以用协程的方式,也可以继承Unity EventSystem中的接口实现。
当鼠标按下的时候以左键为例:
Using System.Collections;
Using System.Collections.Generic;
Using UnityEngine; public class Test:MonoBehavioout{ private Vector3 mousePos;//鼠标位置屏幕 private Vector3 targetPos;//目标位置 private Vector3 offect;//偏移位置鼠标转世界坐标与transform.position的偏移量 private Transform tran;//目标体Transform组件 void Awake(){ tran=transform;//获取Transform组件 } Ienumerator OnMousedown{//Mono中的OnMouseDown可以改成协程 mousePos=new Vector3(Input.mousePosition.x,Input.mousePosition.y,tran.position.z); offect=tran.position-Camera.main.ScreenToWorldPoint(mousePos); while(Input.GetMouseButton(0)){ mousePos=new Vector3(Input.mousePosition.x,Input.mousePosition.y,tran.position.z); targetPos=offect+Camera.main.ScreenToWorldPoint(mousePos); tran.position=targetPos; yield return new WaitForFixedUpdate(); } }
当需要拖拽的物体是UI是,会阻挡射线检测即OnMouseDown等消息机制无法监听到,为了解决这个情况我们需要用到EventTrigger组件,用法类似给Button加上函数。
最重要的是对于UI使用的坐标并非transform组件而是rectTransform组件,故坐标为anchoredPosition才是UI的rect坐标。为了使鼠标坐标能够转换为rectPos坐标需要用到RectTransformUtility.ScreenPointToLocalPointInRectangle()函数,例子如下:
using UnityEngine;
using System.Collections; public class Test:MonoBehaviour{ Canvas canvas;//当前UI所在的画布 RectTransform rectTransform; void Statr(){ rectTransform=transform as RectTransform;//将当transform组件转换为RectTransform canvas=GameObject.Find(“Canvas”).GetComponent<Canvas>();
} void Update(){ Vector2 Pos; if(RectTransformUtility.ScreenPointToLocalPointInRectangle
(canvas.transform as RectTransform,Input.mousePosition,canvas.worldCamera,out pos)) rectTransform.anchoredPosition=pos; }
其中rect 代表当前UI父对象的Rect,screecPoint代表需要转换成LocalPoint的屏幕坐标,cam代表渲染的相机,LocalPoint存储当前的LocalPos。若Canvas渲染模式为Overlay(叠加)模式cam为null。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步