Create a complete p5.js sketch that demonstrates: Hooke’s law (spring oscillation)
Requirements:
Include both setup() and draw() functions
Use createCanvas(400, 400) to set canvas size
Add comments explaining key concepts
Make it visually engaging and educational
Use appropriate colors and animations if relevant
Keep code clean and readable
Focus specifically on: Hooke’s law (spring oscillation)
IMPORTANT: Only output the JavaScript code, no explanations or markdown formatting. The code should be self-contained and runnable in the p5.js editor.
Assistant
let mass; // Mass attached to the spring
let k = 0.2; // Spring constant (Hooke's law constant)
let x = 100; // Initial displacement from equilibrium (pixels)
let v = 0; // Initial velocity
let a = 0; // Acceleration
let originX; // Fixed point of the spring (anchor)
let damping = 0.98; // Damping factor to simulate friction/resistance
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// Draw title
fill(50);
noStroke();
text("Hooke's Law: Spring Oscillation", width / 2, 30);
// Calculate force based on Hooke's law: F = -k * x
// x is displacement from equilibrium (mass.x - originX)
let displacement = mass.x - originX;
let force = -k * displacement;
// Using Newton's second law: F = m * a => a = F / m
// Assume mass = 1 for simplicity
a = force;
// Update velocity and position
v += a;
v *= damping; // Apply damping to simulate energy loss
mass.x += v;
// Function to draw a zigzag spring between two points
function drawSpring(x1, y1, x2, y2, coils, amplitude) {
stroke(0, 150, 255);
strokeWeight(3);
noFill();
let dx = x2 - x1;
let dy = y2 - y1;
let length = dist(x1, y1, x2, y2);
let angle = atan2(dy, dx);
push();
translate(x1, y1);
rotate(angle);
beginShape();
vertex(0, 0);
let segmentLength = length / coils;
for (let i = 1; i < coils; i++) {
let x = i * segmentLength;
let y = (i % 2 === 0) ? amplitude : -amplitude;
vertex(x, y);
}
vertex(length, 0);
endShape();