-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparticle.js
More file actions
74 lines (61 loc) · 1.87 KB
/
particle.js
File metadata and controls
74 lines (61 loc) · 1.87 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
65
66
67
68
69
70
71
72
73
74
class Particle {
constructor(x, y, mass) {
this.mass = mass;
this.radius = mass / 2;
this.x = x;
this.y = y;
this.vx = 0;
this.vy = 0;
this.ax = 0;
this.ay = 0;
}
draw() {
ctx.fillStyle = "rgba(95, 95, 250, 1)";
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fill();
}
calculate(forIndex) {
this.ax = 0;
this.ay = 0;
for (let i = 0; i < particles.length; i++) {
if (i !== forIndex) {
let dx = particles[i].x - this.x;
let dy = particles[i].y - this.y;
let distSq = dx * dx + dy * dy;
let dist = Math.sqrt(distSq);
let costheta = (particles[i].x - this.x) / dist;
let sintheta = (particles[i].y - this.y) / dist;
var acceleration;
if (dist > this.radius + particles[i].radius + (gap + 1)) {
acceleration = G * (particles[i].mass) / (distSq + 0.01);
} else {
acceleration = -(G * (particles[i].mass) / (distSq + 0.01)) * (this.radius + particles[i].radius + gap - dist);
if (dist < this.radius + particles[i].radius + 1) {
acceleration -= 0.3;
this.vx *= 0.999;
this.vy *= 0.999;
// console.log('collision');
}
}
this.ax += (acceleration) * costheta;
this.ay += (acceleration) * sintheta;
}
}
this.vx += this.ax * dt;
this.vy += this.ay * dt;
}
updatePosition() {
this.x += this.vx * dt;
this.y += this.vy * dt;
}
}
function generateParticles(N) {
const particles = [];
for (let i = 0; i < N; i++) {
let x = Math.floor(Math.random() * canvas.width);
let y = Math.floor(Math.random() * canvas.height);
particles.push(new Particle(x, y, 16));
}
return particles;
}