Jump Animation is currently not working

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By PabloSa00

Hi! First of all, sorry for disturbing, I am just starting at this and maybe my problem is too noobish heh, I am currently facing a problem where I can’t a way to play my animation “Jump”

extends CharacterBody2D
var speed := 120
var direction := 0.0
var jump := 250
const gravity := 9
@onready var anim := $AnimationPlayer
@onready var sprite := $Sprite2D

func _physics_process(delta):
	direction = Input.get_axis("ui_left","ui_right")
	velocity.x = direction * speed
	if is_on_floor() and Input.is_action_just_pressed("ui_accept"):
		velocity.y -= jump
	if !is_on_floor():
		velocity.y += gravity
	
	move_and_slide()

func _process(delta):
	if Input.is_action_pressed("ui_left"):
		anim.play("Walk")
		sprite.flip_h = true
	elif Input.is_action_pressed("ui_right"):
		anim.play("Walk")
		sprite.flip_h = false
	elif Input.is_action_just_pressed("ui_accept"):
		anim.play("Jump")
	else:
		anim.play("Idle")

I have tried placing it in different location like: under velocity.y -= jump, before velocity.y += gravity, etc but nothing seems to work, thank you in advance, have a good day

Edited to fix forum code formatting.

jgodfrey | 2023-05-26 02:48

:bust_in_silhouette: Reply From: jgodfrey

I assume this is a timing issue. Looking at the code, I see that you’re using is_action_just_pressed() for the jump test. That’ll only fire in the single frame where the jump key press is detected. And, I expect that’s working, and probably IS starting the Jump animation, but …

Assuming no other keys are pressed, when you get to the very next frame, you’ll hit that else block that will cause the Idle animation to play.

So, I’d guess that you get a single (game) frame of your jump animation and then it reverts back to the idle animation if other keys aren’t pressed - or the Walkanimation if you are pressing one of those keys.

Really, you need to think about what you want to happen if a given animation is playing when a new animation is required. Ultimately, the idle animation is probably a “last resort” and should only play if another animation isn’t currently playing.

Something like this should allow that to work:

else:
    if !anim.is_playing():
        anim.play("Idle")

So, only play the idle animation if another animation isn’t currently playing…

You are right, it was silly of me not taking in consideration the idle animation running throughout the frames hahah Thank you very much!

PabloSa00 | 2023-05-26 03:04