Check for Collision in the Game Loop
Game State
When a collision is detected we'll set the game state to game over. We're going to extend the Game
class to track a new state
enum to reflect one of three game states:
GameOver
Playing
Title
- This refers to the state where the player must click to start the game. Like a title screen.
We're also going to store our config in the Game
class as well. This will give a convenient place to access the config values, and only require us to pass a single new value to our entities.
We also added a reset
method to the Game
class to reset the game state when needed.
Collision Response
Let's detect the collision and react:
We don't currently have bird.die()
and ground.stop()
. Let's add those now.
Now for ground. This has a few more changes. When the game is over we want the ground to stop moving, so we'll track whether or not we're currently scrolling.
If we're not scrolling, we just return early in the update
method.
Click Handler Refactor
Now back to main.ts
- we need to update the click handler to reflect our new game states.
This is pretty similar to the way we handled the flap
method in the Bird
class. The game starts in Title
state, and when the player clicks we want to change the state to Playing
. Playing
is pretty basic, just react to clicks and call flap()
like usual. When the game is over, we want to reset the game state and reset the entities.
You should see an error, we need to add the reset()
method to the Bird
class as well:
This will allow us to reset the bird when restarting the game.
Bird and Ground Draw Order
Before we had collision detection, it was handy to see the bird fall in front of the ground. This way we knew where it was. Now that we have collision detection, let's draw the bird before the ground so it appears to sink into it.
We did this purely cause we thought it looked better. It's not necessary if you don't agree.
There you have it! We've got collision detection and a nice complete game flow in place. Next up, the pipes.