All variables should be global (use let/var at top level)
Use standard p5.js function names: createCanvas, background, fill, etc.
NO sketch wrapper function - write direct p5.js code
SIMULATION ACCURACY FOR PENDULUM MOTION:
Use correct physics equations, mathematical relationships, or algorithmic principles
Realistic parameter ranges and default values that make physical sense
Smooth, continuous animations with proper time scaling
Proper scaling and units where applicable
Include scientific constants or realistic coefficients
ENSURE every parameter controlled by sliders affects the simulation visibly
Use appropriate time steps and scaling factors to avoid too-fast animations
TEXT AND DISPLAY REQUIREMENTS:
Show ONLY the simulation title at the top
Display ONLY key physics parameters (velocity, acceleration, force, etc.) - no instructions or explanations
Keep text minimal and clean - maximum 4-5 parameter displays
NO instruction text like "Click to...", "Drag to...", etc.
Use concise parameter labels like "Velocity: 5.2 m/s" not "Current velocity value is 5.2"
Position parameter text neatly in corners or edges, not cluttering the center
VISUAL REQUIREMENTS:
Clear, educational visualization of the concept
Multiple visual elements (trails, vectors, measurements, etc.) that don't conflict
Color coding to distinguish different aspects
Grid lines, axes, or reference markers where helpful
Immediate and obvious visual response to parameter changes
Smooth, realistic motion that matches real-world physics
Proper visual hierarchy - important elements should stand out
Clean, uncluttered display with minimal text
EXAMPLE OF FUNCTIONAL CONTROLS WITH PROPER TIMING:
javascript
// Global variables that ACTUALLY affect simulation
let gravitySlider, dampingSlider;
let gravity = 0.5; // This gets updated by slider
let damping = 0.99; // This gets updated by slider
let resetBtn, pauseBtn;
let isPaused = false;
let timeScale = 0.02; // Control animation speed
function setup() {
createCanvas(400, 400);
// Create sliders that CONTROL the simulation with realistic ranges
gravitySlider = createSlider(0.1, 1.0, 0.4, 0.05);
gravitySlider.position(10, height + 10);
dampingSlider = createSlider(0.9, 1.0, 0.995, 0.001);
dampingSlider.position(10, height + 40);
// Create buttons that DO something - positioned to avoid overlap
resetBtn = createButton('Reset');
resetBtn.position(10, height + 40);
pauseBtn = createButton('Pause/Play');
pauseBtn.position(80, height + 40);
}
function draw() {
background(220);
// ACTUALLY USE the slider values - this is critical!
gravity = gravitySlider.value();
damping = dampingSlider.value();
if (!isPaused) {
// Use gravity and damping in actual physics calculations with proper time scaling
velocity += gravity * timeScale;
velocity *= damping;
position += velocity;
}
// Show ONLY title and key parameters - keep it minimal
fill(0);
textAlign(CENTER);
text('Pendulum Motion', width/2, 20);
textAlign(LEFT);
text('Gravity: ' + gravity.toFixed(2), 10, 40);
text('Velocity: ' + velocity.toFixed(2), 10, 60);
// Draw simulation that responds to parameters with realistic motion
ellipse(position, height/2, 20, 20);
}
// Functions that actually work
function resetSimulation() {
position = width/2;
velocity = 0;
}
function togglePause() {
isPaused = !isPaused;
}
IMPORTANT:
Focus on the specific physics, mathematics, or principles of pendulum motion
Make controls that ACTUALLY matter for understanding the concept
Every slider must control a variable used in the simulation
Every button must perform a visible action
Ensure the simulation behaves realistically and responds to all controls
Use proper time scaling to avoid unrealistically fast animations
Position controls carefully to avoid visual conflicts
Make animations smooth and scientifically accurate
Keep text displays MINIMAL - only title and key parameters
NO instruction text or explanations in the simulation
Only output JavaScript code, no explanations
Use global mode p5.js format (no sketch wrapper)
Position controls below the 400x400 canvas with proper spacing
Generate an accurate, interactive simulation of: pendulum motion with WORKING controls, REALISTIC timing, and MINIMAL text displays
javascript
// Pendulum Motion Simulation - Accurate & Interactive
let canvasSize = 400;
let lengthSlider, massSlider, gravitySlider, dampingSlider, angleSlider, timescaleSlider;
let resetBtn, pauseBtn, presetBtn1, presetBtn2;
let length = 200; // Length of pendulum (m)
let mass = 1; // Mass of bob (kg)
let gravity = 9.81; // Gravity (m/s^2)
let damping = 0.995; // Damping coefficient (dimensionless)
let angle = Math.PI / 4; // Initial angle (radians)
let angularVelocity = 0;
let angularAcceleration = 0;
let originX, originY;
let isPaused = false;
let timeScale = 1; // Realistic time scaling multiplier
// For trail visualization
let trail = [];
let maxTrailLength = 100;
function setup() {
createCanvas(canvasSize, canvasSize);
frameRate(60);
originX = width / 2;
originY = 80;
// Length slider: 50cm to 300cm (0.5m to 3m)
lengthSlider = createSlider(50, 300, 200, 1);
lengthSlider.position(10, height + 10);
lengthSlider.style('width', '120px');
// Mass slider: 0.1kg to 5kg
massSlider = createSlider(0.1, 5, 1, 0.1);
massSlider.position(150, height + 10);
massSlider.style('width', '120px');
// Gravity slider: 0.1 to 20 m/s^2
gravitySlider = createSlider(0.1, 20, 9.81, 0.01);
gravitySlider.position(290, height + 10);
gravitySlider.style('width', '120px');
// Damping slider: 0.90 to 1.00 (dimensionless)
dampingSlider = createSlider(0.90, 1.00, 0.995, 0.001);
dampingSlider.position(10, height + 40);
dampingSlider.style('width', '120px');
// Initial angle slider: 0 to 90 degrees
angleSlider = createSlider(0, 90, 45, 1);
angleSlider.position(150, height + 40);
angleSlider.style('width', '120px');
// Time scale slider: 0.1x to 3x real time
timescaleSlider = createSlider(0.1, 3, 1, 0.01);
timescaleSlider.position(290, height + 40);
timescaleSlider.style('width', '120px');
// Buttons
resetBtn = createButton('Reset');
resetBtn.position(10, height + 75);
resetBtn.mousePressed(resetSim);
pauseBtn = createButton('Pause/Play');
pauseBtn.position(80, height + 75);
pauseBtn.mousePressed(togglePause);
presetBtn1 = createButton('Preset: Small Angle');
presetBtn1.position(180, height + 75);
presetBtn1.mousePressed(presetSmallAngle);
presetBtn2 = createButton('Preset: Large Angle');
presetBtn2.position(320, height + 75);
presetBtn2.mousePressed(presetLargeAngle);
resetSim();
}
function draw() {
background(245);
// Update parameters from sliders (must use slider.value())
length = lengthSlider.value();
mass = massSlider.value();
gravity = gravitySlider.value();
damping = dampingSlider.value();
timeScale = timescaleSlider.value();
// Initial angle slider only affects initial condition when reset or mouse drag
// But allow live update of angle if paused
if (isPaused) {
angle = radians(angleSlider.value());
angularVelocity = 0;
}
// Title
fill(30);
noStroke();
textAlign(CENTER, TOP);
textSize(20);
text('Pendulum Motion', width / 2, 10);
// Draw grid lines (every 50 px)
stroke(220);
strokeWeight(1);
for (let x = 0; x <= width; x += 50) {
line(x, 0, x, height);
}
for (let y = 0; y <= height; y += 50) {
line(0, y, width, y);
}
// Physics update if not paused
if (!isPaused) {
// Equation: θ'' = -(g / L) * sin(θ) - damping * θ'
// Use fixed timestep scaled by deltaTime and timeScale for stability
let dt = (deltaTime / 1000) * timeScale; // seconds
angularAcceleration = (-gravity / (length / 100)) * sin(angle);
angularVelocity += angularAcceleration * dt;
angularVelocity *= damping;
angle += angularVelocity * dt;
}
// Calculate bob position
let bobX = originX + length * sin(angle);
let bobY = originY + length * cos(angle);
// Add to trail
trail.push({ x: bobX, y: bobY });
if (trail.length > maxTrailLength) {
trail.shift();
}
// Draw origin
stroke(50);
strokeWeight(3);
fill(80);
circle(originX, originY, 12);
// Draw rod
stroke(60, 100, 200);
strokeWeight(3);
line(originX, originY, bobX, bobY);
// Draw bob
fill(200, 50, 50);
stroke(150, 0, 0);
strokeWeight(2);
circle(bobX, bobY, mass * 15 + 15); // Size proportional to mass
// Draw trail
noFill();
beginShape();
stroke(200, 50, 50, 100);
strokeWeight(2);
for (let i = 0; i < trail.length; i++) {
vertex(trail[i].x, trail[i].y);
}
endShape();
// Draw vectors: velocity and acceleration at bob
// Velocity vector (tangential)
let velMag = angularVelocity * (length / 100); // m/s
let velDir = angle + HALF_PI;
let velVecX = bobX + velMag * 50 * cos(velDir);
let velVecY = bobY + velMag * 50 * sin(velDir);
stroke(50, 150, 50);
strokeWeight(3);
line(bobX, bobY, velVecX, velVecY);
fill(50, 150, 50);
noStroke();
triangle(
velVecX, velVecY,
velVecX - 8 * cos(velDir - PI / 6), velVecY - 8 * sin(velDir - PI / 6),
velVecX - 8 * cos(velDir + PI / 6), velVecY - 8 * sin(velDir + PI / 6)
);
// Acceleration vector (tangential)
let accMag = angularAcceleration * (length / 100); // m/s^2
let accDir = angle + HALF_PI;
let accVecX = bobX + accMag * 200 * cos(accDir);
let accVecY = bobY + accMag * 200 * sin(accDir);
stroke(200, 150, 0);
strokeWeight(3);
line(bobX, bobY, accVecX, accVecY);
fill(200, 150, 0);
noStroke();
triangle(
accVecX, accVecY,
accVecX - 8 * cos(accDir - PI / 6), accVecY - 8 * sin(accDir - PI / 6),
accVecX - 8 * cos(accDir + PI / 6), accVecY - 8 * sin(accDir + PI / 6)
);
// Draw angle arc near origin
noFill();
stroke(100, 100, 255);
strokeWeight(2);
arc(originX, originY, 60, 60, 0, angle, angle < 0);
// Draw length line measurement
stroke(0);
strokeWeight(1);
line(originX + 5, originY + 5, originX + 5, originY + length);
fill(0);
noStroke();
textAlign(LEFT, CENTER);
textSize(12);
text(`${(length / 100).toFixed(2)} m`, originX + 10, originY + length / 2);
// Display parameters (minimal, neat corners)
fill(30);
noStroke();
textSize(14);
textAlign(LEFT, TOP);
text(`Length: ${(length / 100).toFixed(2)} m`, 10, 30);
text(`Mass: ${mass.toFixed(2)} kg`, 10, 50);
text(`Gravity: ${gravity.toFixed(2)} m/s²`, 10, 70);
text(`Damping: ${damping.toFixed(3)}`, 10, 90);
text(`Angle: ${(degrees(angle)).toFixed(1)}°`, 10, 110);
textAlign(RIGHT, TOP);
text(`Angular Vel: ${angularVelocity.toFixed(3)} rad/s`, width - 10, 30);
text(`Angular Acc: ${angularAcceleration.toFixed(3)} rad/s²`, width - 10, 50);
text(`Time Scale: ${timeScale.toFixed(2)}x`, width - 10, 70);
// Mouse interaction: drag bob to set angle if paused
if (isPaused && mouseIsPressed) {
let dx = mouseX - originX;
let dy = mouseY - originY;
let newAngle = atan2(dx, dy);
angle = newAngle;
angularVelocity = 0;
angleSlider.value(degrees(angle));
}
}
// Reset simulation to slider initial values
function resetSim() {
angle = radians(angleSlider.value());
angularVelocity = 0;
angularAcceleration = 0;
trail = [];
isPaused = false;
}
// Toggle pause/play state
function togglePause() {
isPaused = !isPaused;
if (isPaused) {
angularVelocity = 0;
}
}
// Preset: Small angle (~10 degrees), low damping, normal gravity
function presetSmallAngle() {
lengthSlider.value(200);
massSlider.value(1);
gravitySlider.value(9.81);
dampingSlider.value(0.998);
angleSlider.value(10);
timescaleSlider.value(1);
resetSim();
}
// Preset: Large angle (~75 degrees), moderate damping, Earth gravity
function presetLargeAngle() {
lengthSlider.value(150);
massSlider.value(2);
gravitySlider.value(9.81);
dampingSlider.value(0.990);
angleSlider.value(75);
timescaleSlider.value(1);
resetSim();
}