-
Notifications
You must be signed in to change notification settings - Fork 1
/
ball.js
128 lines (113 loc) · 2.85 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
'use strict'
const G = 6.67 * Math.pow(10, -11)
export default class Ball {
history = []
initialPos = {
x: 0,
y: 0,
}
initialVelocity = {
x: 0,
y: 0,
}
pos = {
x: 0,
y: 0,
}
velocity = {
x: 0,
y: 0,
}
radius = 15
color = '#fff'
mass
isStatic = false
reset(ctx) {
this.history = []
this.pos.x = this.initialPos.x
this.pos.y = this.initialPos.y
this.velocity.x = this.initialVelocity.x
this.velocity.y = this.initialVelocity.y
this.draw(ctx)
}
constructor(
x = 0,
y = 0,
vx = 0,
vy = 0,
mass = 5000000,
radius = 15,
isStatic = false
) {
this.initialPos.x = x
this.initialPos.y = y
this.pos.x = x
this.pos.y = y
this.initialVelocity.x = vx
this.initialVelocity.y = vy
this.velocity.x = vx
this.velocity.y = vy
this.color = randomColor()
this.mass = mass
this.radius = radius
this.isStatic = isStatic
}
draw(ctx) {
ctx.beginPath()
ctx.strokeStyle = '#ccc'
for (const point of this.history) ctx.lineTo(point.x, point.y)
ctx.lineWidth = 1
ctx.stroke()
ctx.fillStyle = this.color
ctx.beginPath()
ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI * 2, true)
ctx.closePath()
ctx.fill()
ctx.lineWidth = 2
ctx.stroke()
}
update(ctx, balls, delta) {
for (const ball of balls)
if (this !== ball)
ball.applyForce(this.calculateForce(ball), this, delta)
this.draw(ctx)
}
distance(ball) {
const d = Math.sqrt(
Math.pow(this.pos.x - ball.pos.x, 2) +
Math.pow(this.pos.y - ball.pos.y, 2)
)
const min = 100
const max = 1000
return Math.min(Math.max(d, min), max)
}
calculateForce(ball) {
return G * ((this.mass * ball.mass) / Math.pow(this.distance(ball), 2))
}
applyForce(force, ball) {
if (this.isStatic) return
this.history.push({
x: this.pos.x,
y: this.pos.y,
})
const direction = {
x: ball.pos.x - this.pos.x,
y: ball.pos.y - this.pos.y,
}
const normalized = normalize(direction)
this.velocity.x += force * normalized.x
this.velocity.y += force * normalized.y
this.pos.x += this.velocity.x
this.pos.y += this.velocity.y
}
}
function normalize(vector) {
const length = Math.sqrt(vector.x * vector.x + vector.y * vector.y)
return {
x: vector.x / length,
y: vector.y / length,
}
}
function randomColor() {
return `hsla(${Math.random() * 360}, 100%, 50%, 0.6)`
}