您好,登錄后才能下訂單哦!
今天不是很忙,研究了一下拖拽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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。