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

Godot新手求助:按下按键玩家无移动,附玩家节点脚本

Godot玩家无法移动的修复方案

你的脚本存在两处关键问题,导致按键后玩家无反应:

  • move_and_collide 未在物理帧循环内执行
    你把move_and_collide(velocity)写在了_physics_process(delta)函数外部,它只会在脚本加载时运行一次,无法随每帧物理更新响应按键输入,自然不会产生移动效果。

  • 速度重置逻辑错误
    无按键输入时,你将velocity直接设为0(标量值),这会把原本的Vector2类型变量改成数值类型,后续修改velocity.x会失效。正确做法是仅重置x轴速度。

另外,为了让移动速度不随帧率波动,建议将速度值乘以delta。

以下是修复后的脚本:

extends CharacterBody2D
var velocity = Vector2.ZERO

func _physics_process(delta):
    # 先重置x轴速度,避免持续移动
    velocity.x = 0
    
    if Input.is_action_pressed("ui_right"):
        velocity.x = 200 * delta
    elif Input.is_action_pressed("ui_left"):
        velocity.x = -200 * delta
    
    # 把移动函数放在物理帧循环内,每帧执行
    move_and_collide(velocity)

如果你更想使用Godot推荐的move_and_slide(自带碰撞处理更友好),可以用这个版本:

extends CharacterBody2D
# 定义移动速度,便于后续调整
var move_speed = 200.0

func _physics_process(delta):
    var velocity = Vector2.ZERO
    
    if Input.is_action_pressed("ui_right"):
        velocity.x = move_speed
    elif Input.is_action_pressed("ui_left"):
        velocity.x = -move_speed
    
    # 乘以delta保证帧率无关
    velocity *= delta
    move_and_slide(velocity)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 22:22:50