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

Unity玩家移动脚本按空格修改DirectionX需多次按压问题

问题原因
  • 第一,你使用了Input.GetKey(KeyCode.Space)检测按键,这个API返回的是当前帧按键是否处于按住状态,只要你按下空格的时间覆盖了多个物理帧,就会反复触发DirectionX的正反切换,大概率按一次就来回切了好几次最终回到原值,看起来就像没触发成功。
  • 第二,Unity的Input输入状态只会在每帧Update执行前刷新,FixedUpdate是物理帧,调用频率和Update不固定同步,就算你用单次按键检测API放在FixedUpdate里,也大概率会丢失按键事件,导致按好几次才能触发一次。
修复方案

把按键检测逻辑移到Update中,使用Input.GetKeyDown检测单次按下事件,位移逻辑仍然保留在FixedUpdate中保证物理运算稳定。
修改后的参考代码如下:

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

public class Player_Movement_script : MonoBehaviour
{
    public float moveSpeed = 1f;
    public float DirectionX=1;
     
    Vector2 DirectionMovement;
   
    // 输入检测放在Update
    void Update()
    {
        // GetKeyDown只在按下的那一帧返回true,不会重复触发
        if (Input.GetKeyDown(KeyCode.Space))
        {
            DirectionX *= -1;
        }
    }

    // 物理位移放在FixedUpdate
    void FixedUpdate()
    {
        DirectionMovement = new Vector2(DirectionX, 1f);
        transform.Translate(DirectionMovement * moveSpeed * Time.deltaTime);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:24:05