Unity 3D游戏如何实现相机启动时始终朝前(不受鼠标位置影响)
解决Unity相机默认朝前的问题
当然可以实现,核心是在游戏加载完成时重置鼠标位置并同步旋转变量,避免初始鼠标位置影响相机朝向。
你的代码目前的问题是:游戏启动时xRot和yRot会直接读取当前鼠标的轴输入值,如果鼠标不在屏幕中心,第一帧的偏移量会立刻改变相机旋转,导致初始朝向不对。
修改方案如下:
- 在
Start()方法里初始化所有旋转变量,确保初始状态为默认朝前 - 启动时锁定鼠标到屏幕中心,重置鼠标输入的初始参考点,避免第一帧读取到错误的偏移量
修改后的完整代码示例:
private float xRot = 0f; private float yRot = 0f; private float xCurrRot = 0f; private float yCurrRot = 0f; private float xRotVelocity = 0f; private float yRotVelocity = 0f; public float mouseSensetive = 100f; public float smoothDampTime = 0.1f; public Transform mainCamera; public Transform Player; void Start() { // 初始化旋转变量,确保初始朝向为默认前方向 xRot = 0f; yRot = 0f; xCurrRot = 0f; yCurrRot = 0f; // 锁定鼠标到屏幕中心,重置鼠标输入参考点 Cursor.lockState = CursorLockMode.Locked; } void LateUpdate () { MouseMove(); } private void MouseMove() { xRot += Input.GetAxis("Mouse Y") * mouseSensetive * Time.deltaTime; yRot -= Input.GetAxis("Mouse X") * mouseSensetive * Time.deltaTime; // 限制上下旋转角度(可选,防止相机过度抬头/低头) xRot = Mathf.Clamp(xRot, -90f, 90f); xCurrRot = Mathf.SmoothDamp(xCurrRot, -xRot, ref xRotVelocity, smoothDampTime); yCurrRot = Mathf.SmoothDamp(yCurrRot, -yRot, ref yRotVelocity, smoothDampTime); mainCamera.transform.rotation = Quaternion.Euler(xCurrRot, yCurrRot, 0f); Player.transform.rotation = Quaternion.Euler(0f, yCurrRot, 0f); }
补充说明:
Cursor.lockState = CursorLockMode.Locked会把鼠标固定在屏幕中心,同时隐藏鼠标光标,如果需要显示光标,可以在后续游戏流程中改为CursorLockMode.None,但启动时锁定是确保初始朝向正确的关键- 代码中加入了
Time.deltaTime,让鼠标灵敏度不受帧率影响,这是Unity视角控制的常规优化 - 可选的
Mathf.Clamp(xRot, -90f, 90f)可以防止玩家把相机转到头顶或脚下,提升操作体验
内容的提问来源于stack exchange,提问作者Mason T-2025
相关产品推荐
相关产品推荐

