You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Godot引擎:脚本控制AnimationPlayer单次播放及按钮动画需求实现

Fixing One-Shot Animation Playback on Hold/Release in Godot

Hey there! Let's get that animation behavior sorted out for you. I can see exactly why your current code is causing the animation to loop—let's break down the issues and adjust things to match what you want:

First, a quick typo fix

Your function is named _physsics_process (missing an "i")—it should be _physics_process to run correctly in Godot. That's an easy one to miss!

Why your current code loops

Right now, every frame that the button is held, you're calling play('LegMove') on your AnimationPlayer. This resets the animation to the start every single frame, making it look like it's looping nonstop. The same happens when you release the button: every frame you call play_backwards, which resets the reverse playback each time.

The solution: Track animation state

We need to add checks to make sure we only trigger the animation (or reverse animation) when it's actually needed—i.e., when the button state changes, or when the animation isn't already playing in the correct direction.

Here's the adjusted code:

extends RigidBody2D

func _physics_process(delta):
    var leg_anim = $Leg/LegAnimation
    
    if Input.is_action_pressed('ui_jump'):
        # Only play the forward animation if:
        # 1. It's not playing at all, OR
        # 2. It's playing in reverse, OR
        # 3. It's playing a different animation
        if not leg_anim.is_playing() or leg_anim.animation_speed < 0 or leg_anim.current_animation != 'LegMove':
            leg_anim.animation_speed = 1.0  # Ensure forward playback speed
            leg_anim.play('LegMove')
    else:
        # Only play the reverse animation if:
        # 1. It's not playing at all, OR
        # 2. It's playing forward, OR
        # 3. It's playing a different animation
        if not leg_anim.is_playing() or leg_anim.animation_speed > 0 or leg_anim.current_animation != 'LegMove':
            leg_anim.animation_speed = -1.0  # Ensure reverse playback speed
            leg_anim.play('LegMove')

A quick note on animation settings

Double-check your LegMove animation in the AnimationPlayer: make sure the Loop option is disabled. If the animation itself is set to loop, even a single play() call will make it repeat, which we don't want here.

How this works

  • When you hold the button, the code will only start the forward animation once—once it finishes playing, it won't restart unless you release and press the button again.
  • When you release the button, it will trigger the reverse animation once, playing back to the starting frame without repeating.

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

火山引擎 最新活动