[Unity菜鸟] 摄像机视角控制
1. 摄像机预览物体 上下左右远近
把CameraFollow脚本赋给Camera,把要观察的对象赋给target
using UnityEngine; using System.Collections; public class CameraFollow : MonoBehaviour { public Transform target; public float targetHeight; public float distance; public int maxDistance; public float minDistance; public float xSpeed; public float ySpeed; public int yMinLimit; public int yMaxLimit; public int zoomRate; public float rotationDampening; private float x; private float y; public CameraFollow() { this.targetHeight = 2f; this.distance = 5f; this.maxDistance = 20; this.minDistance = 2.5f; this.xSpeed = 250f; this.ySpeed = 120f; this.yMinLimit = -20; this.yMaxLimit = 80; this.zoomRate = 20; this.rotationDampening = 3f; } public void Start() { Vector3 eulerAngles = this.transform.eulerAngles; this.x = eulerAngles.y; this.y = eulerAngles.x; if (this.rigidbody) { this.rigidbody.freezeRotation = true; } } public void LateUpdate() { if (this.target) { if (Input.GetMouseButton(1) || Input.GetMouseButton(1)) { this.x += Input.GetAxis("Mouse X") * this.xSpeed * 0.02f; this.y -= Input.GetAxis("Mouse Y") * this.ySpeed * 0.02f; } else { if (Input.GetAxis("Vertical") != (float)0 || Input.GetAxis("Horizontal") != (float)0) { float num = this.target.eulerAngles.y; float num2 = this.transform.eulerAngles.y; this.x = Mathf.LerpAngle(num2, num, this.rotationDampening * Time.deltaTime); } } this.distance -= Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * (float)this.zoomRate * Mathf.Abs(this.distance); this.distance = Mathf.Clamp(this.distance, this.minDistance, (float)this.maxDistance); this.y = ClampAngle(this.y, (float)this.yMinLimit, (float)this.yMaxLimit); Quaternion quaternion = Quaternion.Euler(this.y, this.x, (float)0); Vector3 position = this.target.position - (quaternion * Vector3.forward * this.distance + new Vector3((float)0, -this.targetHeight, (float)0)); this.transform.rotation = quaternion; this.transform.position = position; } } public float ClampAngle(float angle, float min, float max) { if (angle < (float)-360) { angle += (float)360; } if (angle > (float)360) { angle -= (float)360; } return Mathf.Clamp(angle, min, max); } }
2. 摄像机围绕物体旋转
using UnityEngine; using System.Collections; public class CameraVirtual : MonoBehaviour { //旋转的物体 public GameObject building; //用来记录鼠标的位置,以便计算旋转幅度 Vector2 p1, p2; // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(1)) { p1 = new Vector2(Input.mousePosition.x, Input.mousePosition.y);//鼠标右键按下时记录鼠标位置p1 } if (Input.GetMouseButton(1)) { p2 = new Vector2(Input.mousePosition.x, Input.mousePosition.y);//鼠标右键拖动时记录鼠标位置p2 //下面开始旋转,仅在水平方向上进行旋转 float dx = p2.x - p1.x; transform.RotateAround(building.transform.position, Vector3.up, dx * Time.deltaTime); } } }
参考: 1