今天不是很忙,研究了一下拖拽GameObject移动到任意位置,沿x轴和z轴移动,其他的也就不说了,上代码:
using UnityEngine; using System.Collections; public class DragAndDrog : MonoBehaviour { private GameObject target; private bool isMouseDrag; private Vector3 screenPosition; private Vector3 offset; // Use this for initialization void Start () { } // Update is called once per frame void Update () { GameObjectDragAndDrog(); } //任意拖拽 private GameObject ReturnGameObjectDrag(out RaycastHit hit) { target = null; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray.origin, ray.direction * 10, out hit)) { target = hit.collider.gameObject; } return target; } //拖拽Updata private void GameObjectDragAndDrog() { if (Input.GetMouseButtonDown (0)) { RaycastHit hitInfo; target = ReturnGameObjectDrag(out hitInfo); if (target != null) { isMouseDrag = true; screenPosition = Camera.main.WorldToScreenPoint(target.transform.position); offset = target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z)); } } if (Input.GetMouseButtonUp(0)) { isMouseDrag = false; } if (isMouseDrag) { Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z); Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offset; target.transform.localPosition = new Vector3(currentPosition.x, currentPosition.y, currentPosition.z); } } } 本脚本可以加载任意一个对象GameObject,场景中所有带Collider的对象,当鼠标点击拖动时候都可以沿x和z轴拖动。之前,都是要拖动那个GameObject就会写一个脚本挂在上面,今天实现了不用每一个要拖动的GameObject都挂载脚本,也不用将移动的GameObject赋给某个变量。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。