-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathpong.js
76 lines (66 loc) · 1.33 KB
/
pong.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
// @ts-check
kaplay({
background: [255, 255, 128],
});
// add paddles
add([
pos(40, 0),
rect(20, 80),
outline(4),
anchor("center"),
area(),
"paddle",
]);
add([
pos(width() - 40, 0),
rect(20, 80),
outline(4),
anchor("center"),
area(),
"paddle",
]);
// move paddles with mouse
onUpdate("paddle", (p) => {
p.pos.y = mousePos().y;
});
// score counter
let score = 0;
add([
text(score.toString()),
pos(center()),
anchor("center"),
z(50),
{
update() {
this.text = score.toString();
},
},
]);
// ball
let speed = 480;
const ball = add([
pos(center()),
circle(16),
outline(4),
area({ shape: new Rect(vec2(-16), 32, 32) }),
{ vel: Vec2.fromAngle(rand(-20, 20)) },
]);
// move ball, bounce it when touche horizontal edges, respawn when touch vertical edges
ball.onUpdate(() => {
ball.move(ball.vel.scale(speed));
if (ball.pos.x < 0 || ball.pos.x > width()) {
score = 0;
ball.pos = center();
ball.vel = Vec2.fromAngle(rand(-20, 20));
speed = 320;
}
if (ball.pos.y < 0 || ball.pos.y > height()) {
ball.vel.y = -ball.vel.y;
}
});
// bounce when touch paddle
ball.onCollide("paddle", (p) => {
speed += 60;
ball.vel = Vec2.fromAngle(ball.pos.angle(p.pos));
score++;
});