這篇文章主要爲大家詳細介紹了unity實現鼠標拖住3D物體,具有一定的參考價值,感興趣的小夥伴們可以參考一下
本文實例爲大家分享了unity實現鼠標拖住3D物體的具體代碼,供大家參考,具體內容如下
把該腳本直接掛在要拖拽的物體上即可
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ModelDrages : MonoBehaviour { //發射射線的攝像機 private Camera cam; //射線碰撞的物體 private GameObject go; //射線碰撞物體的名字 public static string btnName; private Vector3 screenSpace; private Vector3 offset; private bool isDrage = false; // Use this for initialization void Start () { cam = Camera.main; } // Update is called once per frame void Update () { //整體初始位置 Ray ray = cam.ScreenPointToRay(Input.mousePosition); //從攝像機發出到點擊座標的射線 RaycastHit hitInfo; if (isDrage == false) { if(Physics .Raycast (ray,out hitInfo)) { //劃出射線 只有在Scene視圖中才能看到 Debug.DrawLine(ray.origin, hitInfo.point); go = hitInfo.collider.gameObject; print(btnName); screenSpace = cam.WorldToScreenPoint(go.transform.position); offset = go.transform.position - cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z)); //物體的名字 btnName = go.name; //組件的名字 } else { btnName = null; } } if(Input.GetMouseButton(0)) { Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z); Vector3 currentPosition = cam.ScreenToWorldPoint(currentScreenSpace) + offset; if (btnName != null) { go.transform.position = currentPosition; } isDrage = true; } else { isDrage = false; } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。