let mass; // Mass attached to the spring
let k = 0.2; // Spring constant (Hooke's law constant)
let x = 150; // Initial displacement from equilibrium (pixels)
let v = 0; // Initial velocity
let a = 0; // Acceleration
let equilibriumX; // Equilibrium position on canvas
function setup() {
createCanvas(400, 400);
equilibriumX = width / 2; // Center of canvas is equilibrium point
mass = {
x: equilibriumX + x,
y: height / 2,
radius: 30
};
textAlign(CENTER, CENTER);
textSize(16);
}
function draw() {
background(240);
// Calculate force based on Hooke's law: F = -k * x
// x is displacement from equilibrium
let displacement = mass.x - equilibriumX;
let force = -k * displacement;
// Newton's second law: F = m * a => a = F / m
// Assume mass m = 1 for simplicity
a = force;
// Update velocity and position using simple Euler integration
v += a;
v *= 0.95; // Damping to simulate friction/resistance
mass.x += v;
// Draw spring as a series of zig-zags between fixed point and mass
drawSpring(equilibriumX, height / 2, mass.x, height / 2, 20, 10);
// Draw fixed point (wall)
fill(100, 100, 255);
rect(equilibriumX - 10, height / 2 - 40, 20, 80, 5);
// Draw mass
fill(255, 100, 100);
stroke(180, 0, 0);
strokeWeight(2);
ellipse(mass.x, mass.y, mass.radius * 2);
// Draw equilibrium line
stroke(150);
strokeWeight(1);
line(equilibriumX, height / 2 - 80, equilibriumX, height / 2 + 80);
// Display information text
noStroke();
fill(50);
text("Hooke's Law: F = -k * x", width / 2, 30);
text("Spring constant k = " + k.toFixed(2), width / 2, 50);
text("Displacement x = " + displacement.toFixed(1) + " px", width / 2, 70);
text("Force F = " + force.toFixed(2), width / 2, 90);
text("Velocity v = " + v.toFixed(2), width / 2, 110);
text("Acceleration a = " + a.toFixed(2), width / 2, 130);
// Instruction
fill(0, 150);
textSize(14);
text("Click and drag the mass to displace the spring", width / 2, height - 20);
}
// Draw a spring as zig-zag line between two points
function drawSpring(x1, y1, x2, y2, coils, amplitude) {
stroke(50, 150, 200);
strokeWeight(3);
noFill();
let springLength = x2 - x1;
let segmentLength = springLength / coils;
beginShape();
vertex(x1, y1);
for (let i = 1; i < coils; i++) {
let x = x1 + i * segmentLength;
// Alternate amplitude up and down for zig-zag effect
let y = y1 + (i % 2 === 0 ? amplitude : -amplitude);
vertex(x, y);
}
vertex(x2, y2);
endShape();
}
let dragging = false;
function mousePressed() {
// Check if mouse is over the mass
let d = dist(mouseX, mouseY, mass.x, mass.y);
if (d < mass.radius) {
dragging = true;
v = 0; // Reset velocity while dragging
}
}
function mouseDragged() {
if (dragging) {
// Limit dragging to horizontal movement only, near equilibrium line
mass.x = constrain(mouseX, equilibriumX - 200, equilibriumX + 200);
}
}
function mouseReleased() {
dragging = false;
}