How do I make the player play the animatedsprite2d in 4 directions

Godot Version

Godot 4.2

Question

I’m making the game which is action rpg but I don’t know how to program the player play the animatedsprite2d in different direction, I use animatedsprite2d instead of sprite cuz making the entire spritesheet is complicated to me, when the player Is idle after moving right, the animation that the player is playing is “rightidle”, when the player move right, the animation that the player is playing is “rightmove”, when the player move in different direction which in case is down, the animation that the player is playing is “downmove”, when the player stop moving down, the idle animation Is different which in case “downidle”, can anyone help me with “gdscript” script?

You probably want to look into scripting a simple state machine.

If you google around for “gdscript state machine” you’ll find lots of examples.

Here is a simple example that might help you get started:

# player_script.gd
extends Node2D

enum Facing {
	LEFT,
	RIGHT,
	UP,
	DOWN,
}

enum MovementState {
	IDLE,
	MOVING,
}

var current_facing: Facing = Facing.DOWN

var current_move_state: MovementState = MovementState.IDLE

@onready var animated_sprite_2d: AnimatedSprite2D = $AnimatedSprite2D

func _process(delta: float) -> void:
	# TODO: Replace these inputs with custom actions in Project Settings -> Input Map
	if Input.is_action_pressed("ui_left"):
		current_facing = Facing.LEFT
		current_move_state = MovementState.MOVING
		
	elif Input.is_action_pressed("ui_right"):
		current_facing = Facing.RIGHT
		current_move_state = MovementState.MOVING
		
	elif Input.is_action_pressed("ui_up"):
		current_facing = Facing.UP
		current_move_state = MovementState.MOVING
		
	elif Input.is_action_pressed("ui_down"):
		current_facing = Facing.DOWN
		current_move_state = MovementState.MOVING
		
	else:
		current_move_state = MovementState.IDLE
	
	match current_move_state:
		MovementState.IDLE:
			match current_facing:
				Facing.LEFT: animated_sprite_2d.play("leftidle")
				Facing.RIGHT: animated_sprite_2d.play("rightidle")
				Facing.UP: animated_sprite_2d.play("upidle")
				Facing.DOWN: animated_sprite_2d.play("downidle")
		
		MovementState.MOVING:
			match current_facing:
				Facing.LEFT: animated_sprite_2d.play("leftmove")
				Facing.RIGHT: animated_sprite_2d.play("rightmove")
				Facing.UP: animated_sprite_2d.play("upmove")
				Facing.DOWN: animated_sprite_2d.play("downmove")

Disclaimer: this is just a “getting started” example. You’ll probably need to modify it a bit to work in an actual game.

1 Like