-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathcamera.js
106 lines (91 loc) · 2.19 KB
/
camera.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// @ts-check
// Adjust camera / viewport
// Start game
kaplay();
// Load assets
loadSprite("bean", "/sprites/bean.png");
loadSprite("coin", "/sprites/coin.png");
loadSprite("grass", "/sprites/grass.png");
loadSound("score", "/examples/sounds/score.mp3");
const SPEED = 480;
let score = 0;
// Set the gravity acceleration (pixels per second)
setGravity(2400);
// Setup a basic level, check the 'level' example for more info
const level = addLevel([
"@ = $",
"=======",
], {
tileWidth: 64,
tileHeight: 64,
pos: vec2(100, 200),
tiles: {
"@": () => [
sprite("bean"),
area(),
body(),
anchor("bot"),
"player",
],
"=": () => [
sprite("grass"),
area(),
body({ isStatic: true }),
anchor("bot"),
],
"$": () => [
sprite("coin"),
area(),
anchor("bot"),
"coin",
],
},
});
// Get the player object from tag
const player = level.get("player")[0];
// Will run every frame
player.onUpdate(() => {
// Set the viewport center to player.pos
setCamPos(player.worldPos());
});
// Set the viewport center to player.pos whenever their physics are resolved
player.onPhysicsResolve(() => {
setCamPos(player.worldPos());
});
// When the player collides with a coin object
player.onCollide("coin", (coin) => {
// It does these things
destroy(coin);
play("score");
score++;
// Zoooom in!
setCamScale(2);
});
// Movements
onKeyPress("space", () => {
if (player.isGrounded()) {
player.jump();
}
});
onKeyDown("left", () => player.move(-SPEED, 0));
onKeyDown("right", () => player.move(SPEED, 0));
// Add a ui layer with fixed() component to make the object
// not affected by camera
const ui = add([
fixed(),
]);
// Add a score counter
ui.add([
text("0"),
pos(12),
{
update() {
this.text = score.toString();
},
},
]);
onClick(() => {
// Use toWorld() to transform a screen-space coordinate (like mousePos()) to
// the world-space coordinate, which has the camera transform applied
addKaboom(toWorld(mousePos()));
});