State design pattern

Introduction

Scripting a game can be difficult when there are many states that need to handled, but only one script can be attached to a node at a time. Instead of creating a state machine within the player’s control script, it would make development simpler if the states were separated out into different classes.

There are many ways to implement a state machine with Godot, and some other methods are below:

  • The player can have a child node for each state, which are called when utilized.
  • Enums can be used in conjunction with a match statement.
  • The state scripts themselves could be swapped out from a node dynamically at run-time.

This tutorial will focus only on adding and removing nodes which have a state script attached. Each state script will be an implementation of a different state.

Note

There is a great resource explaining the concept of the state design pattern here: https://gameprogrammingpatterns.com/state.html

Script setup

The feature of inheritance is useful for getting started with this design principle. A class should be created that describes the base features of the player. For now, a player will be limited to two actions: move left, move right. This means there will be two states: idle and run.

Below is the generic state, from which all other states will inherit.

GDScript

  1. # state.gd
  2. extends Node2D
  3. class_name State
  4. var change_state
  5. var animated_sprite
  6. var persistent_state
  7. var velocity = 0
  8. # Writing _delta instead of delta here prevents the unused variable warning.
  9. func _physics_process(_delta):
  10. persistent_state.move_and_slide(persistent_state.velocity, Vector2.UP)
  11. func setup(change_state, animated_sprite, persistent_state):
  12. self.change_state = change_state
  13. self.animated_sprite = animated_sprite
  14. self.persistent_state = persistent_state
  15. func move_left():
  16. pass
  17. func move_right():
  18. pass

A few notes on the above script. First, this implementation uses a setup(change_state, animated_sprite, persistent_state) method to assign references. These references will be instantiated in the parent of this state. This helps with something in programming known as cohesion. The state of the player does not want the responsibility of creating these variables, but does want to be able to use them. However, this does make the state coupled to the state’s parent. This means that the state is highly reliant on whether it has a parent which contains these variables. So, remember that coupling and cohesion are important concepts when it comes to code management.

Note

See the following page for more details on cohesion and coupling: https://courses.cs.washington.edu/courses/cse403/96sp/coupling-cohesion.html

Second, there are some methods in the script for moving, but no implementation. The state script just uses pass to show that it will not execute any instructions when the methods are called. This is important.

Third, the _physics_process(delta) method is actually implemented here. This allows the states to have a default _physics_process(delta) implementation where velocity is used to move the player. The way that the states can modify the movement of the player is to use the velocity variable defined in their base class.

Finally, this script is actually being designated as a class named State. This makes refactoring the code easier, since the file path from using the load() and preload() functions in Godot will not be needed.

So, now that there is a base state, the two states discussed earlier can be implemented.

GDScript

  1. # idle_state.gd
  2. extends State
  3. class_name IdleState
  4. func _ready():
  5. animated_sprite.play("idle")
  6. func _flip_direction():
  7. animated_sprite.flip_h = not animated_sprite.flip_h
  8. func move_left():
  9. if animated_sprite.flip_h:
  10. change_state.call_func("run")
  11. else:
  12. _flip_direction()
  13. func move_right():
  14. if not animated_sprite.flip_h:
  15. change_state.call_func("run")
  16. else:
  17. _flip_direction()

GDScript

  1. # run_state.gd
  2. extends State
  3. class_name RunState
  4. var move_speed = Vector2(180, 0)
  5. var min_move_speed = 0.005
  6. var friction = 0.32
  7. func _ready():
  8. animated_sprite.play("run")
  9. if animated_sprite.flip_h:
  10. move_speed.x *= -1
  11. persistent_state.velocity += move_speed
  12. func _physics_process(_delta):
  13. if abs(persistent_state.velocity.x) < min_move_speed:
  14. change_state.call_func("idle")
  15. persistent_state.velocity.x *= friction
  16. func move_left():
  17. if animated_sprite.flip_h:
  18. persistent_state.velocity += move_speed
  19. else:
  20. change_state.call_func("idle")
  21. func move_right():
  22. if not animated_sprite.flip_h:
  23. persistent_state.velocity += move_speed
  24. else:
  25. change_state.call_func("idle")

Note

Since the Run and Idle states extend from State which extends Node2D, the function _physics_process(delta) is called from the bottom-up meaning Run and Idle will call their implementation of _physics_process(delta), then State will call its implementation, then Node2D will call its own implementation and so on. This may seem strange, but it is only relevant for predefined functions such as _ready(), _process(delta), etc. Custom functions use the normal inheritance rules of overriding the base implementation.

There is a roundabout method for obtaining a state instance. A state factory can be used.

GDScript

  1. # state_factory.gd
  2. class_name StateFactory
  3. var states
  4. func _init():
  5. states = {
  6. "idle": IdleState,
  7. "run": RunState
  8. }
  9. func get_state(state_name):
  10. if states.has(state_name):
  11. return states.get(state_name)
  12. else:
  13. printerr("No state ", state_name, " in state factory!")

This will look for states in a dictionary and return the state if found.

Now that all the states are defined with their own scripts, it is time to figure out how those references that passed to them will be instantiated. Since these references will not change it makes sense to call this new script persistent_state.gd.

GDScript

  1. # persistent_state.gd
  2. extends KinematicBody2D
  3. class_name PersistentState
  4. var state
  5. var state_factory
  6. var velocity = Vector2()
  7. func _ready():
  8. state_factory = StateFactory.new()
  9. change_state("idle")
  10. # Input code was placed here for tutorial purposes.
  11. func _process(_delta):
  12. if Input.is_action_pressed("ui_left"):
  13. move_left()
  14. elif Input.is_action_pressed("ui_right"):
  15. move_right()
  16. func move_left():
  17. state.move_left()
  18. func move_right():
  19. state.move_right()
  20. func change_state(new_state_name):
  21. if state != null:
  22. state.queue_free()
  23. state = state_factory.get_state(new_state_name).new()
  24. state.setup(funcref(self, "change_state"), $AnimatedSprite, self)
  25. state.name = "current_state"
  26. add_child(state)

Note

The persistent_state.gd script contains code for detecting input. This was to make the tutorial simple, but it is not usually best practice to do this.

Project setup

This tutorial made an assumption that the node it would be attached to contained a child node which is an AnimatedSprite. There is also the assumption that this AnimatedSprite has at least two animations, the idle and run animations. Also, the top-level node is assumed to be a KinematicBody2D.

../../_images/llama_run.gif

Note

The zip file of the llama used in this tutorial is here. The source was from piskel_llama, but I couldn’t find the original creator information on that page… There is also a good tutorial for sprite animation already. See 2D Sprite Animation.

So, the only script that must be attached is persistent_state.gd, which should be attached to the top node of the player, which is a KinematicBody2D.

../../_images/state_design_node_setup.png ../../_images/state_design_complete.gif

Now the player has utilized the state design pattern to implement its two different states. The nice part of this pattern is that if one wanted to add another state, then it would involve creating another class that need only focus on itself and how it changes to another state. Each state is functionally separated and instantiated dynamically.