赞
踩
unity实现物品拖拽,3D创景需要注意的是一个屏幕坐标转换为世界坐标和世界坐标转换屏幕坐标,熟悉他们之间的转化,就没什么难度了
从摄像机发射一条射线,通过射线检测到鼠标点击的物体,将物品的世界坐标转换为屏幕坐标
将鼠标的位置为,鼠标点击的X\Y轴和物品的Z给到,然后将鼠标的屏幕坐标转换为世界坐标给到物品在update里面实时更新移动,这样就可以完成物品的拖拽了
- public class Drag : MonoBehaviour
- {
- private int flag = 0;
- private bool b = false;
- private GameObject go;
- Vector3 targetScreenPos;
- Vector3 mousePos;
- void Start()
- {
-
- }
- void Update()
- {
- if(Input.GetMouseButton(0))
- {
- Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
- RaycastHit hit;//射线碰撞到的物体
- if(Physics.Raycast(ray,out hit))
- {
- if(hit.collider.tag == "A"|| hit.collider.tag == "B" || hit.collider.tag == "C")
- {
- go = hit.collider.gameObject;//点击到的物体
- b = true;
- if(flag==0)
- {
- flag = 1;
- }
- else
- {
- flag = 0;
- }
- }
- if(flag==1 && b && go!=null)
- {
- targetScreenPos = Camera.main.WorldToScreenPoint(go.transform.position);//将屏幕坐标转换成世界坐标
- mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, targetScreenPos.z);//鼠标的位置
- go.transform.position = Camera.main.ScreenToWorldPoint(mousePos);//将物体的位置给到鼠标颠倒屏幕的位置
- }
- }
- }
- }
- }

赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。