-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathball.js
More file actions
64 lines (55 loc) · 1.7 KB
/
ball.js
File metadata and controls
64 lines (55 loc) · 1.7 KB
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
export class Ball {
constructor(stageWidth, stageHeight, radius, speed) {
this.radius = radius;
this.vx = speed;
this.vy = speed;
const diameter = this.radius * 2;
this.x = this.radius + (Math.random() * stageWidth - diameter);
this.y = this.radius + (Math.random() * stageHeight - diameter);
}
draw(ctx, stageWidth, stageHeight, block) {
this.x += this.vx;
this.y += this.vy;
this.bounceWindow(stageWidth, stageHeight);
this.bounceBlock(block);
ctx.fillStyle = '#fdd700';
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fill()
}
bounceWindow(stageWidth, stageHeight) {
const minX = this.radius;
const maxX = stageWidth - this.radius;
const minY = this.radius;
const maxY = stageHeight - this.radius;
if (this.x <= minX || this.x >= maxX) {
this.vx *= -1;
this.x += this.vx;
} else if (this.y <= minY || this.y >= maxY) {
this.vy *= -1;
this.y += this.vy;
}
}
bounceBlock(block) {
const minX = block.x - this.radius;
const maxX = block.maxX + this.radius;
const minY = block.y - this.radius;
const maxY = block.maxY + this.radius;
if (this.x > minX && this.x < maxX && this.y >minY && this.y < maxY) {
const x1 = Math.abs(minX - this.x);
const x2 = Math.abs(this.x - maxX);
const y1 = Math.abs(minY - this.y);
const y2 = Math.abs(this.y - maxY);
const min1 = Math.min(x1, x2);
const min2 = Math.min(y1, y2);
const min = Math.min(min1, min2);
if (min == min1) {
this.vx *= -1;
this.x += this.vx;
} else if (min == min2) {
this.vy *= -1;
this.y += this.vy;
}
}
}
}