Jump animation doesnt play if player is stationary

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

I’ve been building on this movement code for a day now and I continously run into a problem where the jump animation does not play if the player is standing still. The code has the player normally walking, and after walking for 2 seconds, the player will speed up. If anybody can walk me through on how to fix it thank you, Here is my code:

(I also supplied a gif of my game)

extends CharacterBody2D

# Variables
@onready var timer = $Timer
@onready var sprite = $AnimatedSprite2D

var SPEED = 100
var JUMP_VELOCITY = -400.0
var timer_started = false
var running = false
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")

func _physics_process(_delta):
	# Handle gravity and jumping
	if not is_on_floor():
		sprite.play("Jump")
		print("Not on ground")
		velocity.y += 25 #gravity * delta
	else:
		print("On ground")
		if velocity.x == 0:
			sprite.play("Idle")
		else:
			if running == true:
				sprite.play("Run")
			else:
				sprite.play("Walk")

	# Handle jumping input
	if Input.is_action_just_pressed("ui_accept") and is_on_floor():
		velocity.y = JUMP_VELOCITY
		if velocity.x == 0:
			sprite.play("Jump")
	# If the player is not on the ground, and not jumping, set their animation to "Jump"
	elif not is_on_floor():
		sprite.play("Jump")

	# Handle movement input
	var direction = Input.get_axis("ui_left", "ui_right")

	if direction:
		velocity.x = direction * SPEED

		if velocity.x < 0:
			sprite.flip_h = true
		elif velocity.x > 0:
			sprite.flip_h = false

		# Start the timer and play the "Walk" animation
		if not timer_started:
			running = false
			sprite.play("Walk")
			timer.start()
			timer_started = true
	else:
		# Stop the timer and play the "Idle" animation
		sprite.play("Idle")
		running = false
		velocity.x = move_toward(velocity.x, 0, SPEED)
		SPEED = 100
		timer.stop()
		timer_started = false

	move_and_slide()

func _on_timer_timeout():
	timer.stop()
	sprite.play("Run")
	running = true
	print("Timer has timed out!")
	SPEED = 200

Based on your explanation and a quick look at the code, the problem could be here:

if Input.is_action_just_pressed("ui_accept") and is_on_floor():
    velocity.y = JUMP_VELOCITY
    if velocity.x == 0:
        sprite.play("Jump")

Specifically, in that if velocity.x == 0 check. Doing an equality check on a floating point value is always potentially dangerous due to normal floating point errors. If that check is failing, you’d get the jump velocity, but not the jump animation - which seems to be what you’ve described.

You could try to change that if check to something like this and see if it helps…

if is_equal_approx(velocity.x, 0):

Details here:

@GlobalScope — Godot Engine (stable) documentation in English

jgodfrey | 2023-03-09 02:12