You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity玩家移动时相机失控问题技术求助

解决Unity玩家移动时相机失控的问题

问题根源分析

  • 玩家移动方向逻辑错误:玩家移动代码中使用脚本自身的transform转换输入方向,而非玩家对象的朝向,导致移动方向与相机控制的玩家旋转完全脱节。
  • 相机未实现位置跟随:相机控制器仅处理了视角旋转逻辑,未添加位置跟随逻辑,玩家移动时相机停留在原地,引发视角失控的直观感受。

修复方案

1. 修正玩家移动代码

将移动方向转换改为基于玩家对象的transform,确保移动方向严格跟随玩家当前朝向:

修改后的PlayerMovement代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    private CharacterController controller;
    public float speed = 5.0f;

    void Start()
    {
        // 直接获取挂载对象(玩家)的CharacterController组件
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (controller == null)
        {
            Debug.LogError("CharacterController not found on the player GameObject.");
            return;
        }

        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        Vector3 inputDirection = new Vector3(horizontalInput, 0.0f, verticalInput);
        // 基于玩家自身朝向转换移动方向
        Vector3 moveDirection = transform.TransformDirection(inputDirection) * speed;
        controller.Move(moveDirection * Time.deltaTime);
    }
}

2. 完善相机控制器,添加位置跟随

在相机控制器中添加位置跟随逻辑,使用LateUpdate执行跟随操作避免帧同步抖动,确保相机始终跟随玩家位置:

修改后的CameraController代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour
{
    public Transform player; 
    public float sensitivity = 2.0f; 
    public Vector2 rotationLimits = new Vector2(-80, 80);
    // 相机与玩家的相对位置偏移,可在Inspector面板可视化调整
    public Vector3 cameraOffset = new Vector3(0, 2f, -5f);

    private float rotationX = 0;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        // 初始化相机到正确位置
        transform.position = player.position + player.TransformDirection(cameraOffset);
    }

    void LateUpdate()
    {
        // 实时更新相机位置,跟随玩家移动
        transform.position = player.position + player.TransformDirection(cameraOffset);

        // 保留原有视角旋转逻辑
        float mouseX = Input.GetAxis("Mouse X") * sensitivity;
        float mouseY = Input.GetAxis("Mouse Y") * sensitivity;

        player.Rotate(Vector3.up * mouseX);

        rotationX -= mouseY;
        rotationX = Mathf.Clamp(rotationX, rotationLimits.x, rotationLimits.y);

        transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
    }
}

3. 场景配置检查

  • 将PlayerMovement脚本直接挂载在玩家对象上。
  • 将CameraController脚本挂载在相机对象上,并在Inspector面板中指定player引用为玩家的Transform组件。
  • 调整cameraOffset参数,设置符合游戏需求的相机与玩家相对位置。

内容的提问来源于stack exchange,提问作者Scooter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 20:22:24