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

FixedUpdate未对玩家Rigidbody2D施加力的问题排查

问题分析与修复方案

核心代码错误

你代码里的targetSpeed计算存在重复乘moveSpeed的问题,导致最终计算出的移动力逻辑异常:

  • 你先在hInput的赋值里已经乘了moveSpeed(Shift状态下还额外乘了1.5倍)
  • 之后又把hInput再乘一次moveSpeed得到targetSpeed,这会让目标速度变成Input.GetAxis * moveSpeed²,完全偏离预期

修复后的代码

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

public class playerMovement : MonoBehaviour
{
    float hInput;
    float moveSpeed = 3;
    float accel = 5f; // 适当增大加速度值,让移动效果更明显
    float decel;
    float movement;
    [SerializeField] Rigidbody2D rb;

    void Start()
    {
        decel = accel * -1f;
    }

    void Update()
    {
        calcMovement(); 
    }

    void calcMovement()
    {
        hInput = Input.GetAxis("Horizontal");
        // 单独处理速度倍率,避免重复乘moveSpeed
        float speedMultiplier = Input.GetKey(KeyCode.LeftShift) ? 1.5f : 1f;
        float targetSpeed = hInput * moveSpeed * speedMultiplier;

        float speedDiff = targetSpeed - rb.velocity.x;
        float accelRate = Mathf.Abs(targetSpeed) > 0.01f ? accel : decel;
        movement = Mathf.Pow(Mathf.Abs(speedDiff) * accelRate, 0.5f) * Mathf.Sign(speedDiff);
    }

    void FixedUpdate()
    {
        Debug.Log(movement);
        rb.AddForce(movement * Vector2.right);
    }
}

额外排查点

如果修复后仍不移动,检查以下设置:

  • 确认Inspector面板中已将Rigidbody2D组件拖入rb变量
  • 检查刚体的Constraints选项,确保没有冻结X轴位置
  • 调整刚体的Mass值,避免质量过大导致力的效果不明显
  • 确保地面(如果有)的碰撞体和摩擦力设置正常,没有阻碍移动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:05:24