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.

BackNext
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
Preview