-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdot.js
86 lines (80 loc) · 2.16 KB
/
dot.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
class Dot {
constructor(x, y, color, ctx) {
this.ctx = ctx;
this.x = x;
this.y = y;
this.vx = 0;
this.vy = 0;
this.color = color;
this.draw();
}
moveFrom(dot, distance, force, step) {
if (distance === 0) {
this.y += (Math.random() - 0.5) * (1 / step);
this.x += (Math.random() - 0.5) * (1 / step);
return;
}
let dx = (dot.x - this.x);
let dy = (dot.y - this.y);
if (settings.wrap) {
if (Math.abs(dx) > (canvas.width * 0.5)) {
let neg = dx / Math.abs(dx);
dx = canvas.width - Math.abs(dx);
dx *= -1 * neg;
}
if (Math.abs(dy) > (canvas.height * 0.5)) {
let neg = dy / Math.abs(dy);
dy = canvas.height - Math.abs(dy);
dy *= -1 * neg;
}
}
let cos = dx / distance;
let sin = dy / distance;
this.vx += cos * force * (1 / step);
this.vy += sin * force * (1 / step);
}
wrap() {
if (this.x > canvas.width) {
this.x = this.x - canvas.width;
}
if (this.x < 0) {
this.x = canvas.width - this.x;
}
if (this.y > canvas.height) {
this.y = this.y - canvas.height;
}
if (this.y < 0) {
this.y = canvas.height - this.y;
}
}
bounce() {
if (this.x > canvas.width || this.x < 0) {
this.x -= this.vx;
this.vx *= -1;
}
if (this.y > canvas.height || this.y < 0) {
this.y -= this.vy;
this.vy *= -1;
}
}
move() {
this.x += this.vx;
this.y += this.vy;
}
draw() {
this.ctx.fillStyle = this.color;
this.ctx.beginPath();
this.ctx.arc(this.x, this.y, settings.radius, 0, 2 * Math.PI);
this.ctx.fill();
}
update() {
this.vx *= settings.friction;
this.vy *= settings.friction;
this.move();
if (settings.wrap) {
this.wrap();
} else {
this.bounce();
}
}
}