VirtualFramework/Assets/Scripts/FreeCameraController.cs
2025-01-13 11:55:37 +08:00

129 lines
3.6 KiB
C#

using UnityEngine;
public class FreeCameraController : MonoBehaviour
{
public static FreeCameraController instance;
// 相机移动速度
public float moveSpeed = 5.0f; // 降低了移动速度
// 相机旋转速度
public float rotateSpeed = 0.05f; // 降低了旋转速度
// X轴旋转的最大范围
public float xRotationLimit = 80.0f;
// Y轴旋转的最大范围
//public float yRotationLimit = 180.0f;
//public float minRotationLimitY = -1;
//public float maxRotationLimitY = -1;
// 是否启用碰撞检测
public bool enableCollision = false; // 默认关闭碰撞检测,根据需要开启
private Vector3 lastMousePosition;
private bool isDragging = false;
private float xRotation = 0.0f;
private float yRotation = 0.0f;
public bool isMov = true;
public bool isRot = true;
private void Awake()
{
instance = this;
DontDestroyOnLoad(this);
Global.appSetting.MouseMoveSpeed.RegisterWithInitValue(v => rotateSpeed = v);
}
void Update()
{
if (isMov)
{
// 相机移动
float horizontal = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;
float vertical = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;
Vector3 move = transform.right * horizontal + transform.forward * vertical;
transform.position += move;
}
if (isRot)
{
if (Input.GetMouseButtonDown(1))
{
lastMousePosition = Input.mousePosition;
isDragging = true;
SyncRotation();
}
if (Input.GetMouseButtonUp(1))
{
isDragging = false;
}
if (isDragging)
{
// 相机旋转
Vector3 mouseDelta = Input.mousePosition - lastMousePosition; // 反转了鼠标差值
lastMousePosition = Input.mousePosition;
xRotation -= mouseDelta.y * rotateSpeed; // 反转了X轴旋转方向
yRotation += mouseDelta.x * rotateSpeed;
// 限制 X 轴旋转范围
xRotation = Mathf.Clamp(xRotation, -xRotationLimit, xRotationLimit);
// 限制 Y 轴旋转范围
//if (minRotationLimitY != -1 && maxRotationLimitY != -1)
//{
// yRotation = Mathf.Clamp(yRotation, minRotationLimitY, maxRotationLimitY);
//}
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
}
}
}
// 公共方法:旋转相机到指定方向
public void LookAtPos(Vector3 direction)
{
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = targetRotation;
SyncRotation();
}
public void Rotate(Vector3 eulerAngels)
{
transform.eulerAngles = eulerAngels;
SyncRotation();
}
public void SyncRotation()
{
Vector3 currentRotation = transform.eulerAngles;
xRotation = currentRotation.x;
yRotation = currentRotation.y;
// 归一化 xRotation 和 yRotation
if (xRotation > 180f)
{
xRotation -= 360f;
}
else if (xRotation < -180f)
{
xRotation += 360f;
}
if (yRotation > 180f)
{
yRotation -= 360f;
}
else if (yRotation < -180f)
{
yRotation += 360f;
}
transform.eulerAngles = new Vector3(xRotation, yRotation, 0);
}
public void SetLock(bool isMov, bool isRot)
{
this.isMov = isMov;
this.isRot = isRot;
}
}