Sidequest

Clearing Pipes

We're going to need to know when a pipe is cleared so we can increment the score at some point. To know if the bird has cleared the pipe, we'll check if the pipes center x position is less than the birds x position.

Modifying the Pipe Class

Let's modify the pipe class to support this:

1
// ...
2
3
export class Pipe {
4
export class Pipe {
5
height: number;
6
boxCollider: BoxCollider;
+
cleared = false;
8
game: Game;
9
position: Vector2d;
10
rimSpriteData: SpriteData;
11
sliceSpriteData: SpriteData;
12
spriteSheet: HTMLImageElement;
13
type: "top" | "bottom";
14
15
constructor(options: PipeOptions) {
16
// ...
17
}
18
+
get centerX() {
+
return this.position.x + this.rimSpriteData.width / 2;
+
}
22
23
// ...
24
}

Noticed the getter centerX, we'll use this to check if the pipe has been cleared in the game loop.

Tracking Cleared Pipes

In the game loop, lets iterate over the pipes and check if they have been cleared. If they have we'll log to the console for now:

1
// ...
2
3
/**
4
* The game loop.
5
*/
6
const frame = (hrt: DOMHighResTimeStamp) => {
7
// ...
8
9
if (didBirdHitGround || didBirdHitPipe) {
10
bird.die();
11
ground.stop();
12
pipeManager.stop();
13
game.state = GameState.GameOver;
+
} else {
+
for (const [pipeIndex, pipe] of pipeManager.pipes.entries()) {
+
if (pipe.cleared) {
+
continue;
+
}
+
+
const nextPipe = pipeManager.pipes[pipeIndex + 1];
+
+
if (pipe.centerX < bird.position.x) {
+
pipe.cleared = true;
+
nextPipe.cleared = true;
+
+
console.log("cleared");
+
}
+
}
+
}
+
+
// ...
32
};
33
34
// ...

If the bird hasn't collided with the ground or a pipe, we'll check if the pipes have been cleared. If they have, we'll log to the console.

Notice we're processing the pipes in pairs. We always set nextPipe to the next pipe in the array using pipeIndex + 1. If the pipe has been cleared, we set both pipes cleared to true. This will cause the next pipe to be skipped due to our continue statement. If we didn't do this you'd see the console log twice when clearing a pair of pipes. We don't want that or we'll end up incrementing our score twice.

Now when you test the game, open the dev tools and you should see one message in the console every time the bird clears a pair of pipes.