unity3d简单的相机跟随及视野旋转缩放
1、实现相机跟随主角运动
一种简单的方法是把Camera直接拖到Player下面作为Player的子物体,另一种方法是取得Camera与Player的偏移向量,并据此设置Camera位置,便能实现简单的相机跟随了。
这里我们选取第二种方法,首先给Camera添加一个脚本,取名为FollowPlayer,脚本很简单不做说明了
1 public class FollowPlayer : MonoBehaviour { 2 3 private Transform player; 4 private Vector3 offsetPosition; 5 6 // Use this for initialization 7 void Start () { 8 player = GameObject.FindGameObjectWithTag(“Player”).transform; 9 offsetPosition = transform.position - player.position; 10 transform.LookAt(player.position); 11 } 12 13 // Update is called once per frame 14 void Update () { 15 transform.position = offsetPosition + player.position; 16 17 }
2、视野的缩放
鼠标滚轮向前拉近视野,向后视野变远。原理是设置一个变量distance为偏移向量的模,鼠标滚轮滑动改变distance的值,然后根据distance设置Camera的位置
其中scrollSpeed为定义的一个float变量用于调整缩放的速度
1 private float distance; 2 3 private void ScrollView() 4 { 5 distance = offsetPosition.magnitude; 6 //向前滑动拉近 向后滑动拉远 7 distance -= Input.GetAxis("Mouse ScrollWheel") * scrollSpeed; 8 distance = Mathf.Clamp(distance, MinDistance, MaxDistance); 9 offsetPosition = offsetPosition.normalized * distance; 10 } 11 12 //然后在Update里面调用ScrollView方法
3、视野旋转
采用transform.RotateAround方法,让Camera根据Player的位置旋转
1 private void RotateView() 2 { 3 //鼠标右键按下可以旋转视野 4 if (Input.GetMouseButtonDown(1)) 5 isRotating = true; 6 if (Input.GetMouseButtonUp(1)) 7 isRotating = false; 8 9 if (isRotating) 10 { 11 Vector3 originalPosition = transform.position; 12 Quaternion originalRotation = transform.rotation; 13 transform.RotateAround(player.position, player.up, rotateSpeed * Input.GetAxis("Mouse X")); 14 transform.RotateAround(player.position, transform.right, -rotateSpeed * Input.GetAxis("Mouse Y")); 15 float x = transform.eulerAngles.x; 16 //旋转的范围为10度到80度 17 if (x < 10 || x > 80) 18 { 19 transform.position = originalPosition; 20 transform.rotation = originalRotation; 21 } 22 23 } 24 25 offsetPosition = transform.position - player.position; 26 }