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     // Use this for initialization
13 
14     void Awake(){
15         player = GameObject.FindGameObjectWithTag ("Player").transform;
16     }
17 
18     void Start () {
19         //摄像机朝向player
20         transform.LookAt (player.position);
21         //获取摄像机与player的位置偏移
22         offsetPosition = transform.position - player.position;
23     }
24     
25     // Update is called once per frame
26     void Update () {
27         //摄像机跟随player与player保持相对位置偏移 
28         transform.position = offsetPosition + player.position;
29         ScrollView ();
30     }
31 
32     void ScrollView(){
33         //返回位置偏移的向量长度
34         distance = offsetPosition.magnitude;
35 
36         //根据鼠标滚轮的前后移动获取变化长度
37         distance -= Input.GetAxis ("Mouse ScrollWheel") * scrollSpeed;
38 
39         //限制变化长度的范围在最小为4最大为22之间
40         distance = Mathf.Clamp (distance,4,22);
41 
42         //新的偏移值为偏移值的单位向量*变换长度
43         offsetPosition = offsetPosition.normalized * distance;
44 
45         //打印变化长度
46         Debug.Log (distance);
47     }
48 }
posted @ 2016-06-13 13:34  yuge790615  阅读(2181)  评论(0编辑  收藏  举报