Godot Version
Godot 4.4
Question
I’m making a CharacterStateMachine for a 2D Platformer and on my ground state I have to set the y velocity for my character so my character can jump but when I test it out on my game it crashes because of a breakpoint at line 14 of my ground state code and it’s my jump code I also see that my character is null I also don’t know if my player being it’s own scene is messing with that.
This is the ground state code
extends State
class_name GroundState
@export var jump_power = -400.0
Click on Ground Node to assign Air State on the inspector
@export var air_state : State
func state_input(event : InputEvent):
if(event.is_action_pressed(“jump”)):
jump()
func jump():
character.velocity.y = jump_power
next_state = air_state
This is the regular State
extends Node
class_name State
This allows your state to move
@export var can_move : bool = true
creates the character property in the CharacterStateMachine
var character : CharacterBody2D
var next_state : State
Default State if you don’t overwrite it with a Child Class if you never set up state input in Ground State it will do nothing.
func state_input(event : InputEvent):
pass
func on_enter():
pass
func on_exit():
pass
This is My Character State Machine
extends Node
class_name CharacterStateMachine
Click on CharacterStateMachine Node and on the inspector assign it to the player so all the State Nodes can use it.
@export var character : CharacterBody2D
This is to set your default state and it can be used to switch between the states as you need it to be.
@export var current_state : State
var states : Array[State]
This checks if the child nodes are a state and instantly adds any child nodes that are states to the array of states.
func _ready():
for child in get_children():
if(child is State):
states.append(child)
# Set the states up with what they need to function.
child.character = character
# If the child node is not a state it will give us a warning
else:
push_warning("Child " + child.name + "is not a State for CharacterStateMachine")
constantly checks if a current state has a next state set
func _physics_process(delta):
if(current_state.next_state != null):
switch_states(current_state.next_state)
func check_if_can_move():
return current_state.can_move
func switch_states(new_state : State):
if(current_state != null):
current_state.on_exit()
current_state.next_state = null # when you re enter an old state that the next state is cleared so it won’t try to switch again.
current_state = new_state
current_state.on_enter()
when the State Machine gets access to the input events we just pass that along the current state that’s active in the machine.
func _input(event : InputEvent):
current_state.state_input(event)


