鼠标控制相机绕目标点旋转,远近拉近

代码如下:

 1   public class CameraController :SingletonMono<CameraController>
 2     {
 3         [Header("目标位置")]
 4         public Transform target;
 5         [Header("旋转X轴")]
 6         public float mouse_x = 0;
 7         [Header("旋转Y轴")]
 8         public float mouse_y = 0;
 9         [Header("X轴最小旋转值")]
10         public float xMinLimit; 
11         [Header("X轴最大旋转值")]
12         public float xMaxLimit;
13         [Header("摄像机与目标点距离")]
14         public float distance;
15         [Header("摄像机与目标点最大距离")]
16         public float maxDistance;
17         [Header("摄像机与目标点最小距离")]
18         public float minDistance;
19         private float mouseWheelSensitivity=500;//鼠标灵敏度
20 
21         private void Start()
22         {
23             //初始化相机位置
24             Vector3 angles = transform.eulerAngles;//获取自身rotation
25             mouse_y = angles.y;
26             mouse_x = angles.x;
27         }
28         private void LateUpdate()
29         {          
30             if (Input.GetMouseButton(1)) //按下鼠标右键
31             {
32                 mouse_y += Input.GetAxis("Mouse X")*4;
33                 mouse_x -= Input.GetAxis("Mouse Y")*4 ;
34                 mouse_x = ClampAngle(mouse_x, xMinLimit, xMaxLimit);
35             }
36             else if (Input.GetAxis("Mouse ScrollWheel") != 0) //鼠标滚轮缩放功能   
37             {
38                 distance -= Input.GetAxis("Mouse ScrollWheel") * mouseWheelSensitivity;
39                 distance = Mathf.Clamp(distance, minDistance, maxDistance);
40             }
41             if (mouse_x <= 1)  //保证鼠标在地图上方
42             {
43                 mouse_x = 1;
44             }
45             Quaternion Rotation= Quaternion.Euler(mouse_x, mouse_y, 0);
46             Vector3 disVector = new Vector3(0.0f, 0.0f, -distance);
47             Vector3 position = Rotation * disVector + target.position;
48 
49             transform.rotation = Quaternion.Lerp(transform.rotation, Rotation, Time.deltaTime * 5);
50             transform.position = Vector3.Lerp(transform.position, position, Time.deltaTime * 5);
51         }
52 
53         static float ClampAngle(float angle, float min, float max)
54         {
55             if (angle < -360)
56                 angle += 360;
57             if (angle > 360)
58                 angle -= 360;
59             return Mathf.Clamp(angle, min, max);
60         }
61     }

 

posted @ 2021-04-09 15:51  一路繁华的夏ˇ  阅读(193)  评论(0)    收藏  举报