Can't figure out where to put jump animation

Godot Version

4.2

Question

where to put jump animation in this code. I tried everything i can think of, it either dosen’t play or gets stuck at first frame


extends CharacterBody2D

@onready var animated_sprite_2d = $AnimatedSprite2D

const speed = 550
const jump_power = -2000
const acc = 50
const friction = 70
const gravity = 120
const max_jump = 2
var current_jumps = 1

func _physics_process(delta):
	var input_dir :Vector2 = input()
	if input_dir != Vector2.ZERO:
		accelerate(input_dir)
		animated_sprite_2d.animation = "run"
	else:
		add_friction()
		animated_sprite_2d.animation = "idle"
	player_movement()
	jump()
	
func input() ->  Vector2:
	var input_dir = Vector2.ZERO
	
	input_dir.x = Input.get_axis("ui_left", "ui_right")
	input_dir = input_dir.normalized()
	return input_dir
	
func accelerate(direction):
	velocity = velocity.move_toward(speed * direction, acc)

func add_friction():
	velocity = velocity.move_toward(Vector2.ZERO, friction)
	
func player_movement():
	move_and_slide()
	
func jump():
	if Input.is_action_just_pressed("ui_up"):
		if current_jumps < max_jump:
			velocity.y = jump_power
			current_jumps = current_jumps + 1
	else:
		velocity.y += gravity
	
	if is_on_floor():
		current_jumps = 1

What code did you use to play the jump animation?

I’d do animated_sprite_2d.play('jump') (or whatever the animation is called)

That’s because you’re calling jump every frame.

Move this jump code under input.

I don’t understand why gravity is only applied when jumping. Remove else and move this under the physics process.

Why are these in separate functions? You can move all those under the physics process.

From experience, it is better to change animations from somewhere they will be called just once after button press is detected, like in the input () function with Input.is_action_just_pressed. Most movement animations are actually just loops anyway, so you only need to call them once.

Calling animation change in the physics_process every time a condition is meant will cause you problems. For example, in your code, as long as the player is moving, animated_sprite_2d.animation = “run” will be called every frame. For a running animation, you may not notice is constantly restarting the animation, but for other animations like jump, you will definitely notice.

Thanks! Iam just a beginner. I just followed a tutorial and can not understand most of the code here