8 - Input

It's time to have the bird jump when we click (or tap) the screen!

Sprite methods like loop have a getInputs parameter which returns an object of what inputs are being pressed in the current frame. We want to access inputs.pointer which has information about the mouse (or touch on mobile).

When the pointer has just been pressed (which only happens for one frame) we return a different value of the birdGravity state to update gravity, thus giving our bird a jump upwards. Give it a try!

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, 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) {
23 birdGravity = -12;
24 }
25
26 return {
27 birdGravity,
28 birdY,
29 };
30 },
31
32 render({ state }) {
33 return [
34 Bird({
35 id: "bird",
36 x: birdX,
37 y: state.birdY,
38 }),
39 ];
40 },
41});
42
Preview