Game states

As a matter of style, and to help modularize your code, I recommend structuring your game loop like this:

  1. //Set the game state
  2. state = play;
  3. //Start the game loop
  4. app.ticker.add(delta => gameLoop(delta));
  5. function gameLoop(delta){
  6. //Update the current game state:
  7. state(delta);
  8. }
  9. function play(delta) {
  10. //Move the cat 1 pixel to the right each frame
  11. cat.vx = 1
  12. cat.x += cat.vx;
  13. }

You can see that the gameLoop is calling a function called state 60 times per second. What is the state function? It’s been assigned to play. That means all the code in the play function will also run at 60 times per second.

Here’s how the code from the previous example can be re-factored to this new model:

  1. //Define any variables that are used in more than one function
  2. let cat, state;
  3. function setup() {
  4. //Create the `cat` sprite
  5. cat = new Sprite(resources["images/cat.png"].texture);
  6. cat.y = 96;
  7. cat.vx = 0;
  8. cat.vy = 0;
  9. app.stage.addChild(cat);
  10. //Set the game state
  11. state = play;
  12. //Start the game loop
  13. app.ticker.add(delta => gameLoop(delta));
  14. }
  15. function gameLoop(delta){
  16. //Update the current game state:
  17. state(delta);
  18. }
  19. function play(delta) {
  20. //Move the cat 1 pixel to the right each frame
  21. cat.vx = 1
  22. cat.x += cat.vx;
  23. }

Yes, I know, this is a bit of head-swirler! But, don’t let it scare you and spend a minute or two walking through in your mind how those functions are connected. As you’ll see ahead, structuring your game loop like this will make it much, much easier to do things like switching game scenes and levels.