Unity Game窗口中還原Scene窗口攝像機操作 強化版


之前寫的那個版本看來真的是不行啊。最近研究了一下官方第一人稱腳本,人家的平滑過渡真的是沒得說。借鑒了一下,寫出來了一個新的比較完美的控制。

之前我們的操作是通過鼠標輸入的開始坐標和轉動坐標。其實官方有一個函數~

1 float yRot = Input.GetAxis("Mouse X");
2 float xRot = Input.GetAxis("Mouse Y");

這就分別能獲取到鼠標的X軸操作和Y軸操作了。

那為什么用yRot獲取X軸,xRot獲取Y軸呢?

左面是鼠標的頂視圖,右邊是Unity中的三維坐標。可以觀察到,鼠標X軸的平移對應的就是Unity中Y軸的旋轉。Y軸同理。

但是還是不能照搬官方的寫法,因為官方的寫法針對的是自身坐標,就是Local。(注:LocalPosition並不等於物體的Local坐標)

Scene窗口的攝像機是針對World的旋轉。

這里就需要轉換一下。

 

首先我們先得到攝像機的目前旋轉角度,我們在Start初始化一下

1     void Start()
2     {
3         CameraR = Camera.main.transform.rotation.eulerAngles;
4     }

在Update中用Vector3的形式修改旋轉

1             //官方腳本
2             float yRot = Input.GetAxis("Mouse X");
3             float xRot = Input.GetAxis("Mouse Y");
4 
5             Vector3 R = CameraR + new Vector3(-xRot, yRot, 0f); //加上旋轉距離
6 
7             CameraR = Vector3.Slerp(CameraR, R, 100f * Time.deltaTime);//平滑過渡
8 
9             transform.rotation = Quaternion.Euler(CameraR);

給出完整腳本

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class CameraCotrel : MonoBehaviour {
 5 
 6     private float Speed = 100f;
 7     private Vector3 CameraR;
 8 
 9     void Start()
10     {
11         CameraR = Camera.main.transform.rotation.eulerAngles;
12     }
13     
14     void Update ()
15     {
16         Vector3 Face = transform.rotation * Vector3.forward;
17         Face = Face.normalized;
18 
19         Vector3 Left = transform.rotation * Vector3.left;
20         Left = Left.normalized;
21 
22         Vector3 Right = transform.rotation * Vector3.right;
23         Right = Right.normalized;
24 
25         if (Input.GetMouseButton(1))
26         {
27             //官方腳本
28             float yRot = Input.GetAxis("Mouse X");
29             float xRot = Input.GetAxis("Mouse Y");
30 
31             Vector3 R = CameraR + new Vector3(-xRot, yRot, 0f);
32 
33             CameraR = Vector3.Slerp(CameraR, R, Speed * Time.deltaTime);
34 
35             transform.rotation = Quaternion.Euler(CameraR);
36         }
37 
38         if (Input.GetKey("w"))
39         {
40             transform.position += Face * Speed * Time.deltaTime;
41         }
42 
43         if (Input.GetKey("a"))
44         {
45             transform.position += Left * Speed * Time.deltaTime;
46         }
47 
48         if (Input.GetKey("d"))
49         {
50             transform.position += Right * Speed * Time.deltaTime;
51         }
52 
53         if (Input.GetKey("s"))
54         {
55             transform.position -= Face * Speed * Time.deltaTime;
56         }
57         
58         if (Input.GetKey("q"))
59         {
60             transform.position -= Vector3.up * Speed * Time.deltaTime;
61         }
62 
63         if (Input.GetKey("e"))
64         {
65             transform.position += Vector3.up * Speed * Time.deltaTime;
66         }
67 
68     }
69 }

 

 

 


免責聲明!

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



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