using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollowing : MonoBehaviour {
[Header("摄像机水平旋转灵敏度")]
[Range(10, 50)]
public float xSensitivity = 10;
[Header("摄像机垂直旋转灵敏度")]
[Range(10, 50)]
public float ySensitivity = 10;
[Header("摄像机缩放的灵敏度")]
public float zSensitivity = 10;
[Header("摄像机垂直旋转的最小角度限制")]
public float minDegress = 10;
[Header("摄像机垂直旋转的最大角度限制")]
public float maxDegress = 60;
[Header("摄像机距离玩家的最小间距")]
public float minDistance = 2;
[Header("摄像机距离玩家的最大间距")]
public float maxDistance = 20;
// 跟随对象
public Transform _player;
// 摄像机与对象偏移量
private Vector3 _offset;
void Start()
{
// 让对象处于屏幕中心
transform.LookAt(_player);
// 计算初始偏移量
_offset = transform.position - _player.position;
}
void Update()
{
// 摄像机跟随玩家
transform.position = _player.position + _offset;
RotateContrli();
ZoomControl();
}
/// <summary>
/// 摄像机旋转
/// </summary>
void RotateContrli()
{
if (Input.GetMouseButton(1))
{
// 获取鼠标水平方向与垂直方向偏移量
float x = Input.GetAxis("Mouse X");
float y = Input.GetAxis("Mouse Y");
// 记录旋转前摄像机初始位置
Vector3 originalPosition = transform.position;
Quaternion originalRotation = transform.rotation;
// 水平方向旋转
transform.RotateAround(_player.position, Vector3.up, x * xSensitivity * Time.deltaTime);
// 垂直方向旋转
transform.RotateAround(_player.position, transform.right, -y * ySensitivity * Time.deltaTime);
// 判断是否越界
float xx = transform.root.eulerAngles.x;
if (xx > maxDegress || xx < minDegress)
{
transform.position = originalPosition;
transform.rotation = originalRotation;
}
// 重新计算偏移量
_offset = transform.position - _player.position;
}
}
void ZoomControl()
{
float z = Input.GetAxis("Mouse ScrollWheel");
// 记录移动前的初始距离
Vector3 originalPosition = transform.position;
// 移动摄像机
transform.Translate(Vector3.forward * z * zSensitivity * Time.deltaTime);
// 判断是否越界
float distance = Vector3.Distance(transform.position, _player.position);
if (distance > maxDistance || distance < minDistance)
transform.position = originalPosition;
// 重新计算偏移量
_offset = transform.position - _player.position;
}
}
网友评论