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

Unity中Player Controller脚本失效:玩家无法移动

Unity角色无法移动的问题修复方案

核心问题分析

你的脚本所有控制逻辑都被包裹在characterController.isGrounded判断中,这意味着只有角色被判定为接地时才会执行移动、旋转和重力操作。如果初始状态下角色没被检测到接地(比如碰撞体尺寸不匹配),或者角色离开地面后,所有控制会完全失效。同时重力仅在接地时应用,不符合物理逻辑。

修正后的脚本

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

[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
    public float speed = 3f;
    public float rotationSpeed = 90f;
    public float gravity = -20f;
    public float jumpSpeed = 15f;

    CharacterController characterController;
    Vector3 moveVelocity;

    void Awake()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        var hInput = Input.GetAxis("Horizontal");
        var vInput = Input.GetAxis("Vertical");

        // 旋转控制不受接地状态影响
        transform.Rotate(transform.up * rotationSpeed * hInput * Time.deltaTime);

        if (characterController.isGrounded)
        {
            // 地面时重置垂直速度,设置前后移动方向
            moveVelocity = transform.forward * speed * vInput;
            
            // 跳跃触发
            if (Input.GetButtonDown("Jump"))
            {
                moveVelocity.y = jumpSpeed;
            }
        }

        // 持续应用重力,无论是否接地
        moveVelocity.y += gravity * Time.deltaTime;

        // 执行角色移动
        characterController.Move(moveVelocity * Time.deltaTime);
    }
}

组件设置调整

从截图看,你的CharacterController参数和默认立方体尺寸不匹配:

  • 默认立方体尺寸为(1,1,1),但你设置的CharacterControllerHeight=2、Center=(0,1,0),会导致碰撞体底部悬空,无法正确触发isGrounded。
  • 建议修改参数:将Height设为1,Center设为(0,0.5,0),让碰撞体与立方体完全贴合。

额外排查项

  • 检查UnityInput Manager,确认Horizontal、Vertical、Jump轴的默认绑定(WASD移动、空格跳跃)未被修改。
  • 确保Player对象未被标记为静态,且没有其他脚本或组件干扰移动逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:15:30