10 - Background

Let's draw a nice blue background for our bird to jump in, instead of the default white background we have now.

We add a t.rectangle Texture as the first Sprite returned in the Level Sprite render method. Sprites are rendered in the order they're returned, so this way our background will always be drawn at the back.

We also want to fill the full view, not just the safe zone. To do this we need a rectangle the width and height of the view, plus the margins. Sprite methods also have a device parameter with a size field just for this.

We could set a position for the rectangle through an x and y prop, but actually the default x: 0, y: 0 position is exactly what we want. In Replay, the origin is directly in the center of the screen, and when you position a Sprite you're positioning its center point too. The y axis is also positive upwards.

BackNext
1import { makeSprite, t } from "@replay/core";
2import { Bird } from "./bird";
3
4const birdX = 0;
5
6export const Level = makeSprite({
7 init() {
8 return {
9 birdY: 10,
10 birdGravity: -12,
11 };
12 },
13
14 loop({ state, getInputs }) {
15 const inputs = getInputs();
16
17 let { birdGravity, birdY } = state;
18
19 birdGravity += 0.8;
20 birdY -= birdGravity;
21
22 if (inputs.pointer.justPressed || inputs.keysJustPressed[" "]) {
23 birdGravity = -12;
24 }
25
26 return {
27 birdGravity,
28 birdY,
29 };
30 },
31
32 render({ state, device }) {
33 const { size } = device;
34 return [
35 t.rectangle({
36 color: "#add8e6",
37 width: size.width + size.widthMargin * 2,
38 height: size.height + size.heightMargin * 2,
39 }),
40 Bird({
41 id: "bird",
42 x: birdX,
43 y: state.birdY,
44 }),
45 ];
46 },
47});
48
Preview