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

Godot中双击按键触发角色奔跑动画方案及代码排查

Godot中实现双击A/D触发奔跑动画及现有代码问题解析

一、你的代码失效原因

  • 局部变量覆盖全局变量:test()函数里写了var run_state = true,这是重新声明的局部变量,完全没修改全局的run_state,导致全局的run_state永远是false,根本进不了奔跑动画的分支。
  • 缺少双击检测逻辑:代码里只根据移动方向判断状态,完全没处理“双击”的时间间隔判断,没法识别玩家的双击操作。
  • 动画播放顺序错误:_physics_process里先调用了$AnimatedSprite.play(),之后才调用test()修改动画,这会导致test()设置的动画被play()覆盖,根本生效不了。

二、正确的双击奔跑实现方案

我们需要记录每个方向键的上次按下时间,通过判断两次按键的时间间隔来触发奔跑,同时处理奔跑状态的维持和切换:

extends KinematicBody2D

export var walk_speed: float = 200
export var run_speed: float = 350
export var double_tap_threshold: float = 0.3  # 双击的时间阈值,可根据手感调整

var velocity = Vector2.ZERO
var is_running = false
# 记录左右方向键的上次按下时间(单位:秒)
var last_left_press = 0.0
var last_right_press = 0.0

func _input(event):
    # 检测左键双击
    if event.is_action_pressed("ui_left"):
        var current_time = OS.get_ticks_msec() / 1000.0
        # 两次按下时间差小于阈值则触发奔跑
        if current_time - last_left_press < double_tap_threshold:
            is_running = true
        last_left_press = current_time
    
    # 检测右键双击
    if event.is_action_pressed("ui_right"):
        var current_time = OS.get_ticks_msec() / 1000.0
        if current_time - last_right_press < double_tap_threshold:
            is_running = true
        last_right_press = current_time
    
    # 松开任意方向键时取消奔跑状态
    if event.is_action_released("ui_left") or event.is_action_released("ui_right"):
        is_running = false

func _physics_process(delta):
    var input_direction = Vector2(
        Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left"),
        Input.get_action_strength("ui_down") - Input.get_action_strength("ui_up")
    ).normalized()

    # 根据奔跑状态切换速度和动画
    if is_running and input_direction.x != 0:
        velocity = input_direction * run_speed
        $AnimatedSprite.animation = "run"
    elif input_direction.length() > 0:
        velocity = input_direction * walk_speed
        $AnimatedSprite.animation = "walk"
    else:
        velocity = Vector2.ZERO
        $AnimatedSprite.animation = "idle"
    
    $AnimatedSprite.play()
    move_and_slide(velocity)

核心逻辑说明:

  • 用_input事件监听按键的按下/释放,精准记录每次按键的时间戳,通过时间差判断是否触发双击。
  • 双击后开启奔跑状态,松开方向键时自动关闭,符合玩家操作习惯。
  • 先设置动画再调用play(),避免动画被覆盖,同时根据奔跑状态动态调整移动速度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:01:05