6 - State
Our game isn't very interesting right now, we need the bird to move! To do this we'll create a Sprite with state.
In a new file level
let's add a Sprite called Level
, which will hold most of our game logic.
The Level
Sprite has an init
method which returns our initial state. We then access our state
in the render
method.
To set the bird's position, we can add an x
and y
coordinate prop
to the Bird
Sprite. All Sprites (including Textures) take an x
and y
prop.
In our top-level Game
Sprite we should also import the Level
Sprite instead of the Bird
Sprite.
- JavaScript
- TypeScript
1import { makeSprite } 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 render({ state }) {
15 return [
16 Bird({
17 id: "bird",
18 x: birdX,
19 y: state.birdY,
20 }),
21 ];
22 },
23});
24
1import { makeSprite } from "@replay/core";
2import { WebInputs } from "@replay/web";
3import { iOSInputs } from "@replay/swift";
4import { Bird } from "./bird";
5
6const birdX = 0;
7
8type LevelState = {
9 birdY: number;
10 birdGravity: number;
11};
12
13export const Level = makeSprite<{}, LevelState, WebInputs | iOSInputs>({
14 init() {
15 return {
16 birdY: 10,
17 birdGravity: -12,
18 };
19 },
20
21 render({ state }) {
22 return [
23 Bird({
24 id: "bird",
25 x: birdX,
26 y: state.birdY,
27 }),
28 ];
29 },
30});
31
Preview