1118OPSSNew/Assets/NewScripts/SceneViewCamera.cs

139 lines
3.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
public class SceneViewCamera : MonoBehaviour
{
[Header("移动设置")]
public float moveSpeed = 10f;
public float fastMoveMultiplier = 2f;
public float elevationSpeed = 5f;
[Header("旋转设置")]
public float rotationSpeed = 180f;
public float minVerticalAngle = -89f;
public float maxVerticalAngle = 89f;
[Header("限制设置")]
public float minHeight = 0.5f;
private Vector3 currentRotation;
private bool isRotating = false;
private Vector3 lastMousePosition;
void Start()
{
// 初始化当前旋转角度
currentRotation = transform.eulerAngles;
// 锁定鼠标到屏幕中心(可选)
// Cursor.lockState = CursorLockMode.Confined;
}
void Update()
{
HandleRotation();
HandleMovement();
ApplyConstraints();
}
void HandleRotation()
{
// 鼠标右键按下时开始旋转
if (Input.GetMouseButtonDown(1))
{
isRotating = true;
lastMousePosition = Input.mousePosition;
// 隐藏鼠标指针
Cursor.visible = false;
}
// 鼠标右键抬起时停止旋转
if (Input.GetMouseButtonUp(1))
{
isRotating = false;
// 显示鼠标指针
Cursor.visible = true;
}
// 执行旋转
if (isRotating)
{
Vector3 mouseDelta = Input.mousePosition - lastMousePosition;
// 计算旋转量
float rotationX = mouseDelta.y * rotationSpeed * Time.deltaTime;
float rotationY = mouseDelta.x * rotationSpeed * Time.deltaTime;
// 更新旋转角度注意X轴对应上下看Y轴对应左右看
currentRotation.x = Mathf.Clamp(currentRotation.x - rotationX, minVerticalAngle, maxVerticalAngle);
currentRotation.y += rotationY;
// 应用旋转
transform.rotation = Quaternion.Euler(currentRotation);
lastMousePosition = Input.mousePosition;
}
}
void HandleMovement()
{
// 计算移动速度(考虑加速)
float currentMoveSpeed = moveSpeed;
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
{
currentMoveSpeed *= fastMoveMultiplier;
}
// 获取输入
float horizontal = Input.GetAxis("Horizontal"); // A/D 或 左右箭头
float vertical = Input.GetAxis("Vertical"); // W/S 或 上下箭头
// 计算移动方向(基于相机当前朝向)
Vector3 moveDirection = Vector3.zero;
if (vertical != 0)
{
moveDirection += transform.forward * vertical;
}
if (horizontal != 0)
{
moveDirection += transform.right * horizontal;
}
// 垂直移动 (Q/E)
if (Input.GetKey(KeyCode.Q))
{
moveDirection += Vector3.down * elevationSpeed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.E))
{
moveDirection += Vector3.up * elevationSpeed * Time.deltaTime;
}
// 应用移动
if (moveDirection != Vector3.zero)
{
// 标准化移动方向以防止斜向移动更快
if (moveDirection.magnitude > 1f)
{
moveDirection.Normalize();
}
transform.position += moveDirection * currentMoveSpeed * Time.deltaTime;
}
}
void ApplyConstraints()
{
// 限制最低高度
Vector3 position = transform.position;
if (position.y < minHeight)
{
position.y = minHeight;
transform.position = position;
}
}
// 可选在Inspector中显示当前状态
}