一:UI元素 ——使用UI事件接口
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class Test : MonoBehaviour,IDragHandler { private GameObject nowDrag_go;//当前拖拽的物体 public void OnDrag(PointerEventData eventData) { FollowMouse(eventData); } private void FollowMouse(PointerEventData eventData) { Vector3 globalMousePos; if (RectTransformUtility.ScreenPointToWorldPointInRectangle(GameObject.Find("Canvas").transform as RectTransform, eventData.position, eventData.pressEventCamera, out globalMousePos)) { nowDrag_go.transform.position = globalMousePos; } } }
二:2D/3D物体——使用生命周期函数
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20using System; using UnityEngine; public class Test : MonoBehaviour { private void Awake() { Input.multiTouchEnabled = false; } private void OnMouseDrag() { //得到摄像机到物体的向量 Vector3 v = transform.position - Camera.main.transform.position; //得到摄像机与物体所在平面的距离 float dis = Vector3.Dot(v, Camera.main.transform.forward); transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, dis)); } }
最后
以上就是甜蜜钢铁侠最近收集整理的关于Unity中实现拖拽操作的全部内容,更多相关Unity中实现拖拽操作内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复