-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPendulum.js
50 lines (44 loc) · 1.79 KB
/
Pendulum.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
class Pendulum {
constructor(length, knobRadius, rotationLength, areaStartAngle, areaEndAngle, dingSound) {
this.length = length;
this.knobRadius = knobRadius;
this.rotationLength = rotationLength;
this.startAngle = 0
this.endAngle = 0
this.color = color(255, 255, 255);
this.useSound = true;
this.dingSound = dingSound;
this.soundRate = 1
this.rotationProgress = 0;
this.direction = "counterclockwise";
}
calcAngles(areaStartAngle, areaEndAngle) {
const offset = Math.abs(Math.asin(this.knobRadius / this.length));
this.startAngle = areaStartAngle + offset;
this.endAngle = areaEndAngle - offset;
}
update(dt) {
const rotationInd = Math.floor(dt / this.rotationLength);
const prevDir = this.direction;
this.direction = "counterclockwise";
if (rotationInd % 2 == 1) this.direction = "clockwise";
if (this.direction != prevDir && this.useSound) {
this.dingSound.rate(this.soundRate);
this.dingSound.play();
}
const timeInCurrentRotation = dt - (rotationInd * this.rotationLength);
this.rotationProgress = timeInCurrentRotation / this.rotationLength;
}
render(x, y) {
const areaAngle = Math.abs(this.endAngle - this.startAngle);
const rotationAngle = this.rotationProgress * areaAngle;
const angle = this.direction == "clockwise" ? this.startAngle + rotationAngle : this.endAngle - rotationAngle;
const dx = Math.cos(angle) * this.length;
const dy = Math.sin(angle) * this.length;
strokeWeight(1.5);
stroke(this.color);
fill(this.color);
line(x, y, x + dx, y + dy);
circle(x + dx, y + dy, this.knobRadius * 2)
}
}