Unity 实现物体拖拽
2024-08-30 16:45:33
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()){
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。
最新文章
- CloudNotes云端个人笔记系统系列文章汇总
- VIM使用(三)
- 为什么MB51本位币金额和采购订单历史本位币金额不一样?
- Java编写的文本编辑器(菜鸟作品)
- SQL学习之空值(Null)检索
- 添加MySql Metat Database 信息
- PHP+Jquery+Ajax 实现动态生成GUID、加载GUID
- 关于MATLAB处理大数据坐标文件2017529
- java对象类型转换和多态性
- 大数据分析中Redis怎么做到220万ops
- 重写Sink合并多行
- [原创]全新IFPGA-Cable----支持Xilinx/Altera/Lattice JTAG和UART
- (转)RBAC权限模型——项目实战
- sys 模块的应用
- 环境部署(七):linux下Jenkins+Git+JDK持续集成
- php-memcached详解
- Delphi控件cxGrid 如何动态创建列?
- numpy数组(4)-二维数组
- mysql进程挂了
- MapGIS计算瓦片数据集
热门文章
- Java的duotaix
- [ERROR] Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.4:install (default-cli) on project kircp-js-plan-resource: The packaging for this project did not assign a file to the bu
- 如何检测指定的Windows服务是否启动
- MINIUI grid学习笔记
- Codeforces Round #575 (Div. 3) D1+D2. RGB Substring (easy version) D2. RGB Substring (hard version) (思维,枚举,前缀和)
- java数据结构2--集合总论
- 【NOIP2016提高A组模拟9.9】总结
- 【leetcode】1224. Maximum Equal Frequency
- DevOps之持续集成Jenkins+Gitlab
- matlab中画三维图形