您好,登錄后才能下訂單哦!
今天不是很忙,研究了一下拖拽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的對象,當(dāng)鼠標(biāo)點(diǎn)擊拖動時候都可以沿x和z軸拖動。之前,都是要拖動那個GameObject就會寫一個腳本掛在上面,今天實(shí)現(xiàn)了不用每一個要拖動的GameObject都掛載腳本,也不用將移動的GameObject賦給某個變量。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。