可以wasd漫游场景,q/e来上升下降,可以调用TeleportAndLookAtTarget来传送到一个Transform附近并注视它,挂到摄像机上就能使用.
using UnityEngine;public class CameraController : MonoBehaviour
{public float moveSpeed = 5f; // 相机移动速度public float sprintMultiplier = 2f; // 按住 Shift 时的加速倍数public float lookSpeedX = 2f; // 水平旋转速度public float lookSpeedY = 2f; // 垂直旋转速度public float upperLookLimit = 80f; // 垂直旋转的最大角度public float lowerLookLimit = -80f; // 垂直旋转的最小角度private float rotationX = 0f;private float rotationY = 0f;private bool isRightMousePressed = false; // 用来检测右键是否按下public Vector3 offset = new Vector3(0, 2, -5);private void Update(){// 检查是否按下右键if (Input.GetMouseButton(1)) // 鼠标右键按下{isRightMousePressed = true;}else{isRightMousePressed = false;}// 只有在按住右键的情况下,才允许旋转if (isRightMousePressed){// 旋转相机rotationX -= Input.GetAxis("Mouse Y") * lookSpeedY; // 垂直旋转rotationY += Input.GetAxis("Mouse X") * lookSpeedX; // 水平旋转// 限制垂直旋转的范围rotationX = Mathf.Clamp(rotationX, lowerLookLimit, upperLookLimit);// 设置相机的旋转transform.localRotation = Quaternion.Euler(rotationX, rotationY, 0);}// 获取是否按住 Shift 键来加速移动bool isSprinting = Input.GetKey(KeyCode.LeftShift);// 根据是否按住 Shift 键来调整移动速度float currentMoveSpeed = isSprinting ? moveSpeed * sprintMultiplier : moveSpeed;// 相机前后左右移动(WASD)float moveX = Input.GetAxis("Horizontal") * currentMoveSpeed * Time.deltaTime; // A/D 左右float moveZ = Input.GetAxis("Vertical") * currentMoveSpeed * Time.deltaTime; // W/S 前后// 上下升降(Q/E)float moveY = 0f;if (Input.GetKey(KeyCode.Q)) // Q 键升{moveY = currentMoveSpeed * Time.deltaTime;}if (Input.GetKey(KeyCode.E)) // E 键降{moveY = -currentMoveSpeed * Time.deltaTime;}// 移动相机transform.Translate(moveX, moveY, moveZ);}// 传送摄像机并让它注视目标public void TeleportAndLookAtTarget(Transform target){// 设置摄像机的位置,并确保它在目标物体的偏移位置transform.position = target.position + offset;// 让摄像机注视目标物体transform.LookAt(target);Quaternion currentRotation = transform.localRotation;rotationX = currentRotation.eulerAngles.x;rotationY = currentRotation.eulerAngles.y;// 处理 rotationX 范围(确保不超出 0 到 360 度)if (rotationX > 180) rotationX -= 360;if (rotationY > 180) rotationY -= 360;}
}