How do I make an entity change between the different animations in relation to an enemy

Godot Version

Godot 4.4

Question

We are making a tower defense game, and we made several idle and attacking animations for different angles, I was wondering if there’s a way to switch between these animations according to certain angles ranges for when the enemy entity enters the tower range.



Any help will be greatly appreciated!

I think this is a great case for using an AnimationPlayer with an AnimationTree.

If you want to stay with AnimatedSprite2D you need to create some sort of translation-method which takes an angle as an input and returns the corresponding AnimationName.
Something like this:

var animation_translation: Dictionary = {
	0.0: "Right",
	PI/4: "Bottom Right",
	PI/4*2: "Bottom",
	PI/4*3: "Bottom Left",
	PI: "Left",
	PI/4*5: "Top Left",
	PI/4*6: "Top",
	PI/4*7: "Top Right",
}

func translate_to_animation(angle: float) -> String: # angle in radians
	angle = snappedf(angle, PI/4) ## Snaps the angle to a quarter of PI for 8-directional Animations
	return animation_translation[angle]

I havent tested this. This also doesnt consider negative angles. Take it as an example