Unity3d--第三人称摄像机常用控制

 1 using UnityEngine;
 2 using System.Collections;
 3 /*
 4  * 第三人称摄像机常用控制
 5 */
 6 public class CameraCS : MonoBehaviour {
 7 
 8     private Transform player;
 9     private Vector3 offsetPosition;
10     private float distance;
11     private float scrollSpeed = 10; //鼠标滚轮速度
12     private bool isRotating; //开启摄像机旋转
13     private float rotateSpeed = 2; //摄像机旋转速度
14     // Use this for initialization
15 
16     void Awake(){
17         player = GameObject.FindGameObjectWithTag ("Player").transform;
18     }
19 
20     void Start () {
21         //摄像机朝向player
22         transform.LookAt (player.position);
23         //获取摄像机与player的位置偏移
24         offsetPosition = transform.position - player.position;
25     }
26     
27     // Update is called once per frame
28     void Update () {
29         //摄像机跟随player与player保持相对位置偏移 
30         transform.position = offsetPosition + player.position;
31         //摄像机的旋转
32         RotateView ();
33         //摄像机的摄影控制
34         ScrollView ();
35     }
36 
37     void ScrollView(){
38         //返回位置偏移的向量长度
39         distance = offsetPosition.magnitude;
40 
41         //根据鼠标滚轮的前后移动获取变化长度
42         distance -= Input.GetAxis ("Mouse ScrollWheel") * scrollSpeed;
43 
44         //限制变化长度的范围在最小为4最大为22之间
45         distance = Mathf.Clamp (distance,4,22);
46 
47         //新的偏移值为偏移值的单位向量*变换长度
48         offsetPosition = offsetPosition.normalized * distance;
49 
50         //打印变化长度
51         Debug.Log (distance);
52     }
53 
54     void RotateView(){
55         //获取鼠标在水平方向的滑动
56         Debug.Log(Input.GetAxis ("Mouse X"));
57         //获取鼠标在垂直方向的滑动
58         Debug.Log(Input.GetAxis("Mouse Y"));
59 
60         //按下鼠标右键开启旋转摄像机
61         if (Input.GetMouseButtonDown(1)) {
62             isRotating = true;
63         }
64 
65         //抬起鼠标右键关闭旋转摄像机
66         if (Input.GetMouseButtonUp(1)) {
67             isRotating = false;
68         }
69 
70         if (isRotating) {
71 
72             //获取摄像机初始位置
73             Vector3 pos = transform.position;
74             //获取摄像机初始角度
75             Quaternion rot = transform.rotation;
76 
77             //摄像机围绕player的位置延player的Y轴旋转,旋转的速度为鼠标水平滑动的速度
78             transform.RotateAround(player.position,player.up,Input.GetAxis("Mouse X") * rotateSpeed);
79 
80             //摄像机围绕player的位置延自身的X轴旋转,旋转的速度为鼠标垂直滑动的速度
81             transform.RotateAround (player.position, transform.right, Input.GetAxis ("Mouse Y") * rotateSpeed);
82 
83             //获取摄像机x轴向的欧拉角
84             float x = transform.eulerAngles.x;
85 
86             //如果摄像机的x轴旋转角度超出范围,恢复初始位置和角度
87             if (x<10 || x>80) {
88                 transform.position = pos;
89                 transform.rotation = rot;
90             }
91         }
92 
93         //更新摄像机与player的位置偏移
94         offsetPosition = transform.position - player.position;
95     }
96 }
posted @ 2016-06-13 15:50  yuge790615  阅读(2441)  评论(0编辑  收藏  举报