-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpuck.js
83 lines (74 loc) · 1.92 KB
/
puck.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
class Puck {
constructor() {
this.x = width / 2;
this.y = height / 2;
this.xspeed = 0;
this.yspeed = 0;
this.r = 12;
this.reset();
}
checkPaddleLeft(p) {
if (
this.y - this.r < p.y + p.h / 2 &&
this.y + this.r > p.y - p.h / 2 &&
this.x - this.r < p.x + p.w / 2
) {
if (this.x > p.x) {
let diff = this.y - (p.y - p.h / 2);
let rad = radians(45);
let angle = map(diff, 0, p.h, -rad, rad);
this.xspeed = 5 * cos(angle);
this.yspeed = 5 * sin(angle);
this.x = p.x + p.w / 2 + this.r;
}
}
}
checkPaddleRight(p) {
if (
this.y - this.r < p.y + p.h / 2 &&
this.y + this.r > p.y - p.h / 2 &&
this.x + this.r > p.x - p.w / 2
) {
if (this.x < p.x) {
let diff = this.y - (p.y - p.h / 2);
let angle = map(diff, 0, p.h, radians(225), radians(135));
this.xspeed = 5 * cos(angle);
this.yspeed = 5 * sin(angle);
this.x = p.x - p.w / 2 - this.r;
}
}
}
update() {
this.x += this.xspeed;
this.y += this.yspeed;
}
reset() {
this.x = width / 2;
this.y = height / 2;
let angle = random(-PI / 4, PI / 4);
this.xspeed = 5 * Math.cos(angle);
this.yspeed = 5 * Math.sin(angle);
if (random(1) < 0.5) {
this.xspeed *= -1;
}
}
edges() {
if (this.y < 0 || this.y > height) {
this.yspeed *= -1;
}
if (this.x - this.r > width) {
ding.play();
leftscore++;
this.reset();
}
if (this.x + this.r < 0) {
ding.play();
rightscore++;
this.reset();
}
}
show() {
fill(255);
ellipse(this.x, this.y, this.r * 2);
}
}