108 lines
3.2 KiB
C#
108 lines
3.2 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 isLock = false;
|
|
|
|
private void Awake()
|
|
{
|
|
instance = this;
|
|
DontDestroyOnLoad(this);
|
|
|
|
Global.appSetting.MouseMoveSpeed.RegisterWithInitValue(v => rotateSpeed = v);
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (isLock == false)
|
|
{
|
|
// 相机移动
|
|
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 (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;
|
|
transform.eulerAngles = currentRotation;
|
|
//minRotationLimitY = currentRotation.y - yRotationLimit / 2;
|
|
//maxRotationLimitY = currentRotation.y + yRotationLimit / 2;
|
|
}
|
|
|
|
public void SetLock(bool isLock)
|
|
{
|
|
this.isLock = isLock;
|
|
}
|
|
} |