-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathgravity.js
65 lines (53 loc) · 1.41 KB
/
gravity.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
// @ts-check
// Responding to gravity & jumping
// Start kaplay
kaplay();
// Load assets
loadSprite("bean", "/sprites/bean.png");
// Set the gravity acceleration (pixels per second)
setGravity(1600);
// Add player game object
const player = add([
sprite("bean"),
pos(center()),
area(),
// body() component gives the ability to respond to gravity
body(),
]);
onKeyPress("space", () => {
// .isGrounded() is provided by body()
if (player.isGrounded()) {
// .jump() is provided by body()
player.jump();
}
});
// .onGround() is provided by body(). It registers an event that runs whenever player hits the ground.
player.onGround(() => {
debug.log("ouch");
});
// Accelerate falling when player holding down arrow key
onKeyDown("down", () => {
if (!player.isGrounded()) {
player.vel.y += dt() * 1200;
}
});
// Jump higher if space is held
onKeyDown("space", () => {
if (!player.isGrounded() && player.vel.y < 0) {
player.vel.y -= dt() * 600;
}
});
// Add a platform to hold the player
add([
rect(width(), 48),
outline(4),
area(),
pos(0, height() - 48),
// Give objects a body() component if you don't want other solid objects pass through
body({ isStatic: true }),
]);
add([
text("Press space key", { width: width() / 2 }),
pos(12, 12),
]);
// Check out https://kaplayjs.com/doc/BodyComp for everything body() provides