using UnityEngine;
public class CameraController : MonoBehaviour
{
public float maxScroll = 2;
public float minScroll = 10;
public float maxYRotateAngles = 80;
public float minYRotateAngles = 10;
public float rotateSpeed = 5;
public float scrollSpeed = 10;
public Transform targetTransform;
private Vector3 offsetPlayerPos;
private float distance;
private Quaternion currentRotation;
void Start()
{
transform.LookAt(targetTransform);
offsetPlayerPos = transform.position - targetTransform.position;
}
void Update()
{
transform.position = targetTransform.position + offsetPlayerPos;
RotateCamera();
ScrollView();
}
void RotateCamera()
{
if (Input.GetMouseButton(1))
{
//向右滑动时正值,向左滑动是负值。
transform.RotateAround(targetTransform.position, targetTransform.up, rotateSpeed * Input.GetAxis("Mouse X"));
Vector3 originalPos = transform.position;
Quaternion originalRotation = transform.rotation;
transform.RotateAround(targetTransform.position, transform.right, -rotateSpeed * Input.GetAxis("Mouse Y"));//影响的属性有两个,position,rotation;
//限制摄像机垂直滑动的距离;
float x = transform.eulerAngles.x;
if (x < minYRotateAngles || x > maxYRotateAngles)//当超出范围之后,我们将属性归位原来的,就是让旋转⽆效;
{
transform.position = originalPos;
transform.rotation = originalRotation;
}
offsetPlayerPos = transform.position - targetTransform.position;
}
}
void ScrollView()
{
//限制最大缩放
if (Input.GetAxis("Mouse ScrollWheel") < 0 && offsetPlayerPos.magnitude < maxScroll)
{
//获取偏移量的模
distance = offsetPlayerPos.magnitude;
distance += System.Math.Abs(Input.GetAxis("Mouse ScrollWheel")) * scrollSpeed;
//通过获得单位向量*新的偏移模更新偏移信息
offsetPlayerPos = offsetPlayerPos.normalized * distance;
}
//限制最小缩放
if (Input.GetAxis("Mouse ScrollWheel") > 0 && offsetPlayerPos.magnitude > minScroll)
{
//获取偏移量的模
distance = offsetPlayerPos.magnitude;
distance += -System.Math.Abs(Input.GetAxis("Mouse ScrollWheel")) * scrollSpeed;
//通过获得单位向量*新的偏移模更新偏移信息
offsetPlayerPos = offsetPlayerPos.normalized * distance;
}
}
}
unity摄像机旋转缩放功能
最新推荐文章于 2024-09-15 18:54:52 发布