Here is a sample of a 2D walk animation in Godot Engine:
extends AnimatedSprite
# The speed at which the character walks
const WALK_SPEED = 100
# The duration of the walking animation
const ANIMATION_DURATION = 0.5
# The speed at which the character changes direction
const TURN_SPEED = 1.5
# The idle animation
var idle_anim = load("res://characters/player/idle.tres")
# The walking animation
var walk_anim = load("res://characters/player/walk.tres")
# The direction the character is facing
var direction = Vector2.RIGHT
# Whether the character is moving
var moving = false
func _ready():
# Set the idle animation
set_animation(idle_anim)
# Set the animation speed
set_process_animation(true)
set_animation_process_mode(ANIMATION_PROCESS_PHYSICS)
func _physics_process(delta):
# If the character is moving
if moving:
# Set the walking animation
set_animation(walk_anim)
# Update the animation speed
set_animation_speed(WALK_SPEED * delta / ANIMATION_DURATION)
# Move the character
move_and_slide(direction * WALK_SPEED * delta)
else:
# Set the idle animation
set_animation(idle_anim)
# Rotate the character to face the direction it's moving
rotate(TURN_SPEED * delta)
func _input(event):
# If the character is moving
if event.is_action_pressed("ui_right"):
direction = Vector2.RIGHT
moving = true
elif event.is_action_pressed("ui_left"):
direction = Vector2.LEFT
moving = true
elif event.is_action_pressed("ui_up"):
direction = Vector2.UP
moving = true
elif event.is_action_pressed("ui_down"):
direction = Vector2.DOWN
moving = true
else:
moving = false
In the code above, we have an AnimatedSprite node that represents the character.
When the character is moving, we play the walking animation and move the character in the specified direction.
When the character is not moving, we play the idle animation and rotate the character to face the direction it's moving.