本文實(shí)例為大家分享了unity實(shí)現(xiàn)鼠標(biāo)拖住3D物體的具體代碼,供大家參考,具體內(nèi)容如下
把該腳本直接掛在要拖拽的物體上即可
using System.Collections;using System.Collections.Generic;using UnityEngine;public class ModelDrages : MonoBehaviour {//發(fā)射射線的攝像機(jī)private Camera cam;//射線碰撞的物體private GameObject go;//射線碰撞物體的名字public static string btnName;private Vector3 screenSpace;private Vector3 offset;private bool isDrage = false;// Use this for initializationvoid Start (){ cam = Camera.main;}// Update is called once per frame void Update (){ //整體初始位置 Ray ray = cam.ScreenPointToRay(Input.mousePosition); //從攝像機(jī)發(fā)出到點(diǎn)擊坐標(biāo)的射線 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; } }}以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選