unity中實現 通過鼠標的點擊來控制物體的旋轉,移動,放大等。


關於這個問題,我總覺得簡單很好做,但是拿到手里,卻有種有勁兒使不出來的感覺,想了想應該是最近的代碼量有點少了!所以大家一定要多寫代碼啊!就像運動員一樣,要多多鍛煉才是!(更何況是我這樣的新手程序員啊...........)

這里以一個Cube為例吧,首先創建了場景場景中有一個方塊,因為主要是想着如何實現功能,所以這里暫時沒有考慮性能方面!還請讀者能夠自己針對性的修改代碼。

如下圖簡單的場景:

廢話不多說了,上代碼:

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class Rotate01 : MonoBehaviour {
 5 
 6     public GameObject obj;
 7     Ray ray;
 8     // Use this for initialization
 9     void Start () {
10         obj.transform.parent = null;
11     }
12     private float scrow=0;
13     void Update () {
14         ray = Camera.main.ScreenPointToRay(Input.mousePosition);
15         if (Input.GetMouseButton(0))
16         {
17             RaycastHit hit;
18             if (Physics.Raycast(ray, out hit))
19             {
20                 if (hit.transform.tag == "cube")
21                 {
22                     //調試畫出的射線
23                     Debug.DrawLine(transform.position, hit.point);
24                     //觀察射線碰撞點
25                     Debug.Log(hit.point);
26                     //實現鼠標點擊不松開,物體跟隨鼠標移動,但是效果不怎么好
27                     obj.transform.position = new Vector3(hit.point.x, hit.point.y, obj.transform.position.z);
28                     //點擊變色,就是為了提示哪個被點擊了
29                     hit.transform.renderer.material.color = Color.red;                }
30             }
31             else
32             {
33                 obj.transform.parent = null;
34                 obj.renderer.material.color = Color.white;
35             }
36             
37         }
38         
39         if(Input.GetMouseButton(1))
40         {//控制上下左右旋轉
41             obj.transform.Rotate(Vector3.up, -Time.deltaTime * 200 * Input.GetAxis("Mouse X"));
42             obj.transform.Rotate(Vector3.right, Time.deltaTime * 200 * Input.GetAxis("Mouse Y"));
43         }
44         if (Input.GetAxis("Mouse ScrollWheel") != 0&&obj.renderer.material.color==Color.red)
45         {
46             scrow=Input.GetAxis("Mouse ScrollWheel");
47             obj.transform.position += (transform.position - obj.transform.position).normalized * scrow;
48         }
49         
50         
51     }
52 }

我現在也只是一個剛入門的程序員,所以代碼寫的不怎么好,還望包涵哈~~~~

這個就是簡單的效果,點中物體后變色,並且能夠跟着鼠標一起走了(射線只能在scnce面板中看到)

然后我松開左鍵,點住右鍵,物體隨着鼠標的移動而旋轉,各個角度(這里處理的也不是很好,還希望看見的同志,能給些建議,大家一起交流一起進步)

還有拉近與放遠,這里我覺得處理的還行,嘿嘿

點擊一下空白部分,他又變回白色了

這是第一次寫,寫的不好,我會慢慢改進的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM