7 - Game Loop
We have state, but we still don't have movement since the state never changes.
We can update the state in the loop
Sprite method. loop
, which runs 60 times per second, takes an existing state
and returns the next frame's state
. loop
should be a pure function: avoid directly mutating state
.
In our game, every frame of the loop
we're updating the birdY
state, as well as the gravity for a more "flappy" effect. This provides some movement!
You'll need to refresh the preview on the right to see it since our bird is currently falling forever.
- 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 loop({ state }) {
15 let { birdGravity, birdY } = state;
16
17 birdGravity += 0.8;
18 birdY -= birdGravity;
19
20 return {
21 birdGravity,
22 birdY,
23 };
24 },
25
26 render({ state }) {
27 return [
28 Bird({
29 id: "bird",
30 x: birdX,
31 y: state.birdY,
32 }),
33 ];
34 },
35});
36
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 loop({ state }) {
22 let { birdGravity, birdY } = state;
23
24 birdGravity += 0.8;
25 birdY -= birdGravity;
26
27 return {
28 birdGravity,
29 birdY,
30 };
31 },
32
33 render({ state }) {
34 return [
35 Bird({
36 id: "bird",
37 x: birdX,
38 y: state.birdY,
39 }),
40 ];
41 },
42});
43
Preview