14 - Pipes

There's not much challenge to the game now, so let's add some green pipes that move across the screen for the bird to dodge.

As you might have guessed by now, we'll add a Pipe Sprite for that. Each pipe is 2 rectangles with a gap in the middle. We need to do some math to calculate the y coordinate of each rectangle - remembering the y coordinate is the center of the rectangle.

Next we need to add our pipes in the Level Sprite's state, defining it in the init method. Then in the loop method we update the state to move the pipe. Lastly in render we map the pipe state to the Pipe Sprite.

The newPipe function sets a random y coordinate for the pipe gap, which our bird has to jump through. The device parameter has a random field, which works like Math.random. It's important to use Replay's random function to ensure the game works cross-platform.

BackNext
1import { makeSprite, t } from "@replay/core";
2
3export const pipeWidth = 40;
4export const pipeGap = 170;
5
6export const Pipe = makeSprite({
7 render({ props, device }) {
8 const { size } = device;
9 const { pipe } = props;
10
11 const {
12 yUpperTop,
13 yUpperBottom,
14 yLowerTop,
15 yLowerBottom,
16 } = getPipeYPositions(size, pipe.gapY);
17
18 return [
19 t.rectangle({
20 color: "green",
21 width: pipeWidth,
22 height: yUpperTop - yUpperBottom,
23 y: (yUpperTop + yUpperBottom) / 2,
24 }),
25 t.rectangle({
26 color: "green",
27 width: pipeWidth,
28 height: yLowerTop - yLowerBottom,
29 y: (yLowerTop + yLowerBottom) / 2,
30 }),
31 ];
32 },
33});
34
35export function getPipeYPositions(size, gapY) {
36 return {
37 yUpperTop: size.height / 2 + size.heightMargin,
38 yUpperBottom: gapY + pipeGap / 2,
39 yLowerTop: gapY - pipeGap / 2,
40 yLowerBottom: -size.height / 2 - size.heightMargin,
41 };
42}
43
Preview