How to keep same animation while activating a new key in my 2d game? (dw ill explain it)

Godot Version

4

Question

So basically, (I’m new) I’m trying to set up a walk cycle that has just 4 directions:
down, up, left and right.

What I want is very simple, when you’re traveling left for example, it will play the “kid_walk_left” animation. But if you press downwards as well, you will start moving diagonally. But I do not want the walk animation to change until you stop pressing left.

Here’s what I came up with:
I set an input to all the movement keys, so it will only recognize it once, therefore not changing the animation. But if you cycle through the keys while never taking your fingers off completely, you’ll be stuck in the same animation.


	if Input.is_action_just_pressed("all_move_keys"):
		if Input.is_action_pressed("moveright"):
			$AnimatedSprite2d.play("kid_walk_right")
		if Input.is_action_pressed("moveleft"):
			$AnimatedSprite2d.play("kid_walk_left")
		if Input.is_action_pressed("movedown"):
			$AnimatedSprite2d.play("kid_walk_down")
		if Input.is_action_pressed("moveup"):
			$AnimatedSprite2d.play("kid_walk_up")

I know this is like probably super simple, I just don’t know how games normally do it.

Hi,

You can do that by storing the information of what direction should be prioritized. For instance, if you go from idle to moving left, you can define that the horizontal motion is prioritized; if you then move diagonally by pressing another key (up or down), since the horizontal axis is now prioritized, you can keep playing the left walk animation.
If the player somehow presses two keys at the same frame, you can arbitrarily choose an axis to prioritize, it doesn’t matter much imho.

Storing the axis to prioritize can be done using a boolean like horizontalAxisPrioritized or an enum with 3 values, like NONE, HORIZONTAL, VERTICAL. Depends on what you prefer but I guess both techniques would work fine.

This can result in a slightly larger code with more conditional checks, but I think there’s no solution to do that in a few lines of code, and as long as it’s readable and easy to iterate on, it’s very acceptable.

2 Likes