Unity 類似FingerGestures 的相機跟隨功能
來源:
未知 |
責(zé)任編輯:六月芳菲 |
發(fā)布時間: 2018-03-05 11:29 | 瀏覽量:
更多精彩unity教程:http://windermere-rat-removal.com/resource/
最近在做一款VR項目,有一個查看功能,分為自由查看和跟隨查看。
自由查看:
第一人稱自由控制查看。使用firstPersonControl即可。跟隨查看:
攝像機可自由旋轉(zhuǎn)并跟隨查看的物體移動(攝像機不可為子物體)。剛開始使用固定坐標的方法,但攝像機無法自由旋轉(zhuǎn)。后來換用rotatearound,可以自由旋轉(zhuǎn),可一旦物體移動,旋轉(zhuǎn)半徑會拉大。
最后,模仿手勢插件寫了一個方法,代碼如下:
1 public Transform target;
2
3
4 public float minDistance = 1.5f; 5 public float maxDistance = 10.0f;
6
7 public float yawSensitivity =30f;
8 public float pinchSensitivity = 5.0f;
9
10 public float smoothZoomSpeed = 30.0f;
11 public float smoothOrbitSpeed = 10.0f;
12
13 float distance = 5.0f;
14 float yaw = 0;
15 float pitch = 0;
16
17 float idealDistance = 0;
18
19 bool rotate;
20
21 public float IdealDistance
22 {
23 get { return idealDistance; }
24 set { idealDistance = Mathf.Clamp( value, minDistance, maxDistance ); }
25 }
26
27 public float Yaw
28 {
29 get { return yaw; }
30 }
31
32 void Start()
33 {
34 Vector3 angles = transform.eulerAngles;
35
36 distance = IdealDistance = 5f;
37 yaw = angles.y;
38 pitch = 25;
39
40 UpdateCamera();
41 }
42
43
44 void Update()
45 {
46 if (Input.GetMouseButtonDown (1))
47 rotate = true;
48 if (Input.GetMouseButtonUp (1))
49 rotate = false;
50
51 if( rotate )
52 {
53 yaw += Input.GetAxis ("Mouse X") * yawSensitivity;
54 pitch -= Input.GetAxis ("Mouse Y") *pinchSensitivity;
55 }
56
57 IdealDistance -= Mathf.Lerp (0, Input.GetAxis ("Mouse ScrollWheel") * smoothZoomSpeed, Time.deltaTime);
58 IdealDistance = Mathf.Clamp (IdealDistance, minDistance, maxDistance);
59 }
60
61 void LateUpdate()
62 {
63 UpdateCamera ();
64 }
65
66 void UpdateCamera()
67 {
68 distance = Mathf.Lerp (distance, IdealDistance, Time.deltaTime * smoothZoomSpeed);
69
70 Vector3 lookAtPos = target.position;
71 Quaternion rotaetAngle = Quaternion.Euler (pitch, yaw, 0);
72
73 Vector3 desiredPos = lookAtPos - rotaetAngle * new Vector3 (0, 0, distance);
74
75 transform.position = desiredPos;
76 transform.rotation = rotaetAngle;
77
78 transform.LookAt (target);
79 }
80
81 static float ClampAngle( float angle, float min, float max )
82 {
83 if( angle < -360 )
84 angle += 360;
85
86 if( angle > 360 )
87 angle -= 360;
88
89 return Mathf.Clamp( angle, min, max );
90 }
以上,完美實現(xiàn)攝像機跟隨,并可以右鍵旋轉(zhuǎn),滾輪拉近功能。
更多精彩unity教程:http://windermere-rat-removal.com/resource/
-
分享到:
相關(guān)文章
網(wǎng)友評論
全部評論:0條
推薦
熱門