Godot Version
Godot 4.7.2
Question
I’m trying to create a 2D puzzle-platformer where the player character moves automatically to the right using State Machines. I’m also trying to have the player play its “ready” animation right before walkingg, but my character doesn’t move at all, nor does it play its “ready” animation.
Here’s my player’s GDScript code:
extends CharacterBody2D
enum ActionStates { READY, IDLE, WALK, JUMP, FALL, GLIDE }
@onready var animated_sprite_2d: AnimatedSprite2D = $AnimatedSprite2D
var state: ActionStates = ActionStates.READY
const SPEED = 300.0
const JUMP_VELOCITY = -400.0
var glide_gravity := 400.0
var current_gravity := gravity
var gravity: int = ProjectSettings.get_setting("physics/2d/default_gravity")
var direction := 1
func _ready() -> void:
pass
func _physics_process(delta: float) -> void:
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta
match state:
ActionStates.READY:
pass
ActionStates.IDLE:
velocity.x = 0
ActionStates.WALK:
velocity.x = direction * SPEED
move_and_slide()
var should_turn = false
if is_on_wall():
should_turn = true
if should_turn:
turn_around()
$AnimatedSprite2D.scale.x = -1 if velocity.x < 0 else 1
move_and_slide()
func is_hitting_wall() -> bool:
return is_on_wall()
func turn_around():
direction *= -1
func handle_jump():
velocity.y = JUMP_VELOCITY
func set_state(new_state: int) -> void:
var previous_state := state
state = new_state
if previous_state == ActionStates.GLIDE:
current_gravity = gravity
if state == ActionStates.GLIDE:
current_gravity = glide_gravity
func update_state(new_state: int) -> void:
if state == ActionStates.READY:
$AnimatedSprite2D.play("ready")
if state == ActionStates.IDLE:
$AnimatedSprite2D.play("idle")
if state == ActionStates.WALK:
$AnimatedSprite2D.play("walk")
if state == ActionStates.JUMP:
$AnimatedSprite2D.play("jump")
if state == ActionStates.FALL:
$AnimatedSprite2D.play("fall")
func _on_animated_sprite_2d_animation_finished() -> void:
if animated_sprite_2d.animation == "ready":
state = ActionStates.WALK