11 - Rotation
Sprites also accept a rotation
prop, which we can use to improve the visuals of the bird flapping.
The rotation is given in degrees (positive clockwise) and rotates about the anchor point of a Sprite - the anchor point is by default the center point of the Sprite.
Here we can setup the rotation as a little function of the current gravity - a negative rotation to face upwards when moving upwards, and a positive rotation to face downwards when moving downwards.
- JavaScript
- TypeScript
1import { makeSprite, t } 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, device }) {
33 const { size } = device;
34 return [
35 t.rectangle({
36 color: "#add8e6",
37 width: size.width + size.widthMargin * 2,
38 height: size.height + size.heightMargin * 2,
39 }),
40 Bird({
41 id: "bird",
42 x: birdX,
43 y: state.birdY,
44 rotation: Math.max(-30, state.birdGravity * 3 - 30),
45 }),
46 ];
47 },
48});
49
1import { makeSprite, t } 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, device }) {
40 const { size } = device;
41 return [
42 t.rectangle({
43 color: "#add8e6",
44 width: size.width + size.widthMargin * 2,
45 height: size.height + size.heightMargin * 2,
46 }),
47 Bird({
48 id: "bird",
49 x: birdX,
50 y: state.birdY,
51 rotation: Math.max(-30, state.birdGravity * 3 - 30),
52 }),
53 ];
54 },
55});
56
Preview