9 - Keyboard
We can also support pressing the space bar to jump for players using a keyboard through a browser.
To do this we can look at the inputs.keysJustPressed
object to see if the space key was just pressed.
The fields inputs.keysDown
and inputs.keysJustPressed
contain an object which will have a true
value for any key codes pressed. Check out keycode.info for possible key
values.
- 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, 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 }) {
33 return [
34 Bird({
35 id: "bird",
36 x: birdX,
37 y: state.birdY,
38 }),
39 ];
40 },
41});
42
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, getInputs }) {
22 const inputs = getInputs();
23
24 let { birdGravity, birdY } = state;
25
26 birdGravity += 0.8;
27 birdY -= birdGravity;
28
29 if (inputs.pointer.justPressed || inputs.keysJustPressed[" "]) {
30 birdGravity = -12;
31 }
32
33 return {
34 birdGravity,
35 birdY,
36 };
37 },
38
39 render({ state }) {
40 return [
41 Bird({
42 id: "bird",
43 x: birdX,
44 y: state.birdY,
45 }),
46 ];
47 },
48});
49
Preview