-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBall.js
62 lines (51 loc) · 1.72 KB
/
Ball.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
const INITIAL_VELCOTIY = 0.025
const VELOCITY_INCREASE = 0.000005
export default class Ball {
constructor(ballElem) {
this.ballElem = ballElem
this.reset()
}
get x() {
return parseFloat(getComputedStyle(this.ballElem).getPropertyValue("--x"))
}
set x(val) {
this.ballElem.style.setProperty("--x", val)
}
get y() {
return parseFloat(getComputedStyle(this.ballElem).getPropertyValue("--y"))
}
set y(val) {
this.ballElem.style.setProperty("--y", val)
}
rect() {
return this.ballElem.getBoundingClientRect()
}
update(delta, paddleRects) {
this.x += this.direction.x * this.velocity * delta
this.y += this.direction.y * this.velocity * delta
this.velocity += VELOCITY_INCREASE * delta
const rect = this.rect()
if(rect.bottom >= window.innerHeight || rect.top <= 0) {
this.direction.y *= -1
}
if(paddleRects.some(r => isCollision(r, rect))) {
this.direction.x *= -1
}
}
reset() {
this.x = 50
this.y = 50
this.direction = {x: 0}
while(Math.abs(this.direction.x <= 0.2) || Math.abs(this.direction.x > 0.9)) {
const heading = randomNumberBetween(0, 2 * Math.PI)
this.direction = {x: Math.cos(heading), y: Math.sin(heading)}
}
this.velocity = INITIAL_VELCOTIY
}
}
function isCollision(rect1, rect2) {
return (rect1.left <= rect2.right && rect1.right >= rect2.left && rect1.top <= rect2.bottom && rect1.bottom >= rect2.top)
}
function randomNumberBetween(min, max) {
return Math.random() * (max-min) + min
}