-
Notifications
You must be signed in to change notification settings - Fork 0
/
ball.js
71 lines (61 loc) · 1.91 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
export class Ball {
static drag = 1;
constructor([posX, posY] = [0,0], [velX, velY] = [0,0], radius = 10, color = 'black') {
this.position = [posX, posY]
this.velocity = [velX, velY]
this.acceleration = [0, 0]
this.force = [0, 0]
this.color = color;
this.radius = radius;
this.fixed = false;
//this.mass = (4/3) * Math.PI * this.#radius ** 3;
this.mass = 4 * Math.PI * this.radius ** 2;
// this.mass = this.#radius ** 2;
}
update(dt) {
if (this.fixed) return;
this.updatePosition(dt);
this.updateVelocity(dt/2);
this.updateAcceleration();
this.updateVelocity(dt);
}
// x(t+dt) = x(t) + v(t)dt + 1/2a(t)dt^2
updatePosition(dt) {
const [x, y] = this.position;
const [vx, vy] = this.velocity;
const [ax, ay] = this.acceleration;
this.position = [
x + vx * dt + 0.5 * ax * dt * dt,
y + vy * dt + 0.5 * ay * dt * dt];
}
// v(t+dt/2) = v(t) + 1/2a(t)dt
updateVelocity(dt) {
const [vx, vy] = this.velocity;
const [ax, ay] = this.acceleration;
this.velocity = [
Ball.drag*(vx + 0.5 * ax * dt),
Ball.drag*(vy + 0.5 * ay * dt)];
}
// a(t+dt) = f(x(t+dt))/m
updateAcceleration() {
const [fx, fy] = this.force;
this.acceleration = [
fx / this.mass,
fy / this.mass];
this.force = [0, 0];
}
applyForce(force) {
if (this.fixed) return;
this.force = [
this.force[0] = force[0],
this.force[1] = force[1]
];
}
paint(context) {
context.beginPath();
context.moveTo(this.position[0], this.position[1]);
context.arc(this.position[0], this.position[1], this.radius, 0, 2 * Math.PI);
context.fillStyle = this.color;
context.fill();
}
}