Fork me on Gitee

Unity 类似FingerGestures 的相机跟随功能

本文原创,转载请注明出处:http://www.cnblogs.com/AdvancePikachu/p/6555188.html

最近在做一款VR项目,有一个查看功能,分为自由查看和跟随查看。

自由查看:

第一人称自由控制查看。使用firstPersonControl即可。

跟随查看:

摄像机可自由旋转并跟随查看的物体移动(摄像机不可为子物体)。

刚开始使用固定坐标的方法,但摄像机无法自由旋转。后来换用rotatearound,可以自由旋转,可一旦物体移动,旋转半径会拉大。

最后,模仿手势插件写了一个方法,代码如下:

 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     }

 

以上,完美实现摄像机跟随,并可以右键旋转,滚轮拉近功能。

posted @ 2017-03-15 17:06  AdvancePikachu  阅读(346)  评论(0编辑  收藏  举报