Pendulum constructor()
The constructor runs once when 'new Pendulum(...)' is called in setup(). It's where you set up all the starting values an object needs before the simulation begins - a foundational pattern in object-oriented JavaScript.
constructor(x, y, length, initialAngle, bobSize, color) {
this.x = x; // Anchor x-coordinate
this.y = y; // Anchor y-coordinate
this.len = length; // Length of the pendulum arm
this.angle = initialAngle; // Current angle from vertical
this.velocity = 0; // Angular velocity
this.bobSize = bobSize; // Diameter of the bob
this.color = color; // Color of the bob
// For trails (glowing circles)
this.bobX = this.x + this.len * sin(this.angle);
this.bobY = this.y + this.len * cos(this.angle);
this.path = []; // Stores past positions of the bob for trails
this.pathLength = 30; // Number of points to keep in the trail
}
Line-by-line explanation (7 lines)
this.x = x;- Stores the fixed anchor point's horizontal position - the pendulum swings around this point.
this.len = length;- Stores how long this particular pendulum's arm is, which directly controls its swing speed.
this.angle = initialAngle;- Sets the starting angle (in radians) that the pendulum begins swinging from - all pendulums start at the same 45-degree angle.
this.velocity = 0;- Angular velocity starts at zero since the pendulum is released from rest.
this.bobX = this.x + this.len * sin(this.angle);- Calculates the bob's initial x position using basic trigonometry: horizontal offset from the anchor equals arm length times the sine of the angle.
this.path = [];- Creates an empty array that will store the bob's recent positions to draw a fading trail.
this.pathLength = 30;- Sets how many past positions are remembered - this controls how long the glowing trail appears.