Game states
As a matter of style, and to help modularize your code, I recommend structuring your game loop like this:
//Set the game state
state = play;
//Start the game loop
app.ticker.add(delta => gameLoop(delta));
function gameLoop(delta){
//Update the current game state:
state(delta);
}
function play(delta) {
//Move the cat 1 pixel to the right each frame
cat.vx = 1
cat.x += cat.vx;
}
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:
//Define any variables that are used in more than one function
let cat, state;
function setup() {
//Create the `cat` sprite
cat = new Sprite(resources["images/cat.png"].texture);
cat.y = 96;
cat.vx = 0;
cat.vy = 0;
app.stage.addChild(cat);
//Set the game state
state = play;
//Start the game loop
app.ticker.add(delta => gameLoop(delta));
}
function gameLoop(delta){
//Update the current game state:
state(delta);
}
function play(delta) {
//Move the cat 1 pixel to the right each frame
cat.vx = 1
cat.x += cat.vx;
}
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.