Game states
See also: Game loop
Games states help you arrange the game into logical groupings
- LOADING
- BUILD MAP – make map, then gameObjects
- PLAYING
- OVER
Only swap between states when necesary, and only the bits that are necessary – e.g.
//Set the game's current state to `play`:
let state = play;
function gameLoop(){
//Loop this function at 60 frames per second
requestAnimationFrame(gameLoop);
//Update the current game state:
state();
//Render the stage to see the animation
renderer.render(stage);
}
function play(){
//Move the sprite 1 pixel to the right each frame
anySprite.x += 1;
}
```
…structuring your game loop like this will make it much, much easier to do things such as switching game scenes and levels. It means that you can completely change what your game or application is doing by simply pointing the state variable to any other function that contains the next bit of code you want to run.
HTML
sets up a base structure to then fill and modify with JS code
e.g. place holders for various aspects of the project
Game structure
Use multiple 2d arrays to store various elements of the game
- a game map array
- a game object array
Map code
And, have a set of map codes for items
Each one of these aligns to a sprite number
| let EMPTY = 0; let FLOOR = 1; let BOX = 2; let WALL = 3; let ALIEN = 4; let BOMB = 5; |
An example structure
canvas and drawing surface
game map array
game object array
map code
tile cell size
Render
Managing levels for maps
Have an array to hold the map and map objects arrays
So long as the ‘exit’ on one map, matches the ‘entry’ (or, start point) on the next map, it should be all good.
But if you have multiple entry/exit points?
Tile map editors
Tiled
Or, create your own JS one
Swapping between maps
this is ONE way to do it…
In Phaser for example – just swap the map data, not the whole ‘level’ scene
this is a good tutorial: https://www.youtube.com/watch?v=bJ166s6qFVU
no need to make a scene for each map
all you need to do is reset the game scene
detect when entering certain areas
restart game scene
update map and position data
in tiled – make a layer called ‘transportation’ with a game object
The basic logic is:
- create a ‘transportation layer’ object which will hold a collection of all the identified transportation objects
- get the transportationLayer data from the map data
- map to load
- tileSet image to use
- spawnX location
- spawnY location
- create custom collisions for each of the transportation objects
- add in a call back function which is called when there is an overlap between the objects and the player
- save the game state in a ‘new game state’
- position X to teleport to
- position Y to teleport to
- previous map position
- health
- coins
- previous position
- current frame of char animation
- current facingDirection of char
- map to load
- save the game state in a ‘new game state’
- restart scene (with new map data)