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:
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', 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
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 with WORKING controls, REALISTIC timing, and MINIMAL text displays
javascript
// Pendulum simulation with realistic physics and interactive controls
let canvasW = 400;
let canvasH = 400;
// Pendulum physical variables
let originX, originY;
let length; // Length of pendulum (m)
let mass; // Mass of bob (kg)
let gravity; // Gravity acceleration (m/s^2)
let damping; // Damping coefficient (dimensionless, 0-1)
let angle; // Current angle (rad)
let angularVelocity; // Angular velocity (rad/s)
let angularAcceleration; // Angular acceleration (rad/s^2)
let timeScale; // Time scaling factor for simulation speed
// Sliders and buttons
let lengthSlider, massSlider, gravitySlider, dampingSlider, angleSlider, timeScaleSlider;
let resetBtn, pauseBtn, presetBtn1, presetBtn2;
let isPaused = false;
// Constants
const gEarth = 9.81; // Earth gravity m/s^2
function setup() {
createCanvas(canvasW, canvasH);
frameRate(60);
originX = width / 2;
originY = 80;
// Initialize default parameters
length = 1.5; // meters
mass = 1.0; // kg
gravity = gEarth;
damping = 0.995;
angle = PI / 4; // 45 degrees
angularVelocity = 0;
angularAcceleration = 0;
timeScale = 1.0;
// Create sliders with realistic ranges and default values
lengthSlider = createSlider(0.5, 3.0, length, 0.01);
lengthSlider.position(10, height + 10);
lengthSlider.style('width', '120px');
massSlider = createSlider(0.1, 5.0, mass, 0.1);
massSlider.position(150, height + 10);
massSlider.style('width', '120px');
gravitySlider = createSlider(0.1, 20.0, gravity, 0.1);
gravitySlider.position(290, height + 10);
gravitySlider.style('width', '100px');
dampingSlider = createSlider(0.90, 1.00, damping, 0.0005);
dampingSlider.position(10, height + 40);
dampingSlider.style('width', '120px');
angleSlider = createSlider(-PI, PI, angle, 0.01);
angleSlider.position(150, height + 40);
angleSlider.style('width', '120px');
timeScaleSlider = createSlider(0.1, 3.0, timeScale, 0.01);
timeScaleSlider.position(290, height + 40);
timeScaleSlider.style('width', '100px');
// 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: Earth');
presetBtn1.position(180, height + 75);
presetBtn1.mousePressed(() => {
lengthSlider.value(1.5);
massSlider.value(1.0);
gravitySlider.value(9.81);
dampingSlider.value(0.995);
angleSlider.value(PI / 4);
timeScaleSlider.value(1.0);
resetSim();
});
presetBtn2 = createButton('Preset: Moon');
presetBtn2.position(280, height + 75);
presetBtn2.mousePressed(() => {
lengthSlider.value(1.5);
massSlider.value(1.0);
gravitySlider.value(1.62);
dampingSlider.value(0.998);
angleSlider.value(PI / 4);
timeScaleSlider.value(1.0);
resetSim();
});
}
function draw() {
background(245);
// Update parameters from sliders
length = lengthSlider.value();
mass = massSlider.value();
gravity = gravitySlider.value();
damping = dampingSlider.value();
timeScale = timeScaleSlider.value();
// If user moves angle slider manually, update angle and reset velocity
if (abs(angleSlider.value() - angle) > 0.001) {
angle = angleSlider.value();
angularVelocity = 0;
}
// Physics timestep (seconds)
// Use deltaTime (ms) scaled by timeScale, convert to seconds
let dt = (deltaTime / 1000) * timeScale;
dt = constrain(dt, 0, 0.05); // limit max timestep for stability
if (!isPaused) {
// Pendulum equation: angular acceleration = -(g / L) * sin(theta) - damping * angularVelocity
angularAcceleration = (-gravity / length) * sin(angle) - (1 - damping) * angularVelocity;
// Semi-implicit Euler integration for stability
angularVelocity += angularAcceleration * dt;
angularVelocity *= damping; // damping applied here
angle += angularVelocity * dt;
// Keep angle within -PI to PI for numeric stability
if (angle > PI) angle -= TWO_PI;
else if (angle < -PI) angle += TWO_PI;
// Update angle slider to reflect simulation (avoid feedback loop)
angleSlider.value(angle);
}
// Calculate bob position in pixels
// Scale length to pixels: 1 meter = 150 pixels approx
let pxPerMeter = 150;
let lenPx = length * pxPerMeter;
let bobX = originX + lenPx * sin(angle);
let bobY = originY + lenPx * cos(angle);
// Draw grid lines for reference (every 0.5 m)
stroke(200);
strokeWeight(1);
for (let i = 0; i <= 6; i++) {
let yGrid = originY + i * 0.5 * pxPerMeter;
line(originX - 150, yGrid, originX + 150, yGrid);
}
// Draw origin point
stroke(0);
strokeWeight(2);
fill(50);
ellipse(originX, originY, 8, 8);
// Draw rod
stroke(30, 90, 180);
strokeWeight(3);
line(originX, originY, bobX, bobY);
// Draw bob with mass-dependent size (scale radius from 15 to 40 px)
let bobRadius = map(mass, 0.1, 5, 15, 40);
fill(180, 50, 50);
stroke(120, 30, 30);
strokeWeight(2);
ellipse(bobX, bobY, bobRadius * 2, bobRadius * 2);
// Draw trail of bob (store last positions)
drawTrail(bobX, bobY);
// Draw vectors: velocity and acceleration as arrows at bob
drawVectors(bobX, bobY, angularVelocity, angularAcceleration, lenPx);
// Title
noStroke();
fill(0);
textAlign(CENTER, CENTER);
textSize(20);
text('Pendulum', width / 2, 30);
// Display key parameters top-left and top-right corners
textSize(14);
textAlign(LEFT, TOP);
fill(0);
// Angular velocity in rad/s and deg/s
let angVelDeg = degrees(angularVelocity);
text('Angle: ' + degrees(angle).toFixed(1) + '°', 10, 50);
text('Angular Vel: ' + angularVelocity.toFixed(3) + ' rad/s', 10, 70);
text('Angular Acc: ' + angularAcceleration.toFixed(3) + ' rad/s²', 10, 90);
textAlign(RIGHT, TOP);
text('Length: ' + length.toFixed(2) + ' m', width - 10, 50);
text('Gravity: ' + gravity.toFixed(2) + ' m/s²', width - 10, 70);
text('Damping: ' + damping.toFixed(4), width - 10, 90);
text('Mass: ' + mass.toFixed(2) + ' kg', width - 10, 110);
text('Time Scale: ' + timeScale.toFixed(2) + 'x', width - 10, 130);
}
// Trail variables
let trail = [];
const maxTrailLength = 80;
function drawTrail(x, y) {
trail.push(createVector(x, y));
if (trail.length > maxTrailLength) {
trail.shift();
}
noFill();
stroke(180, 50, 50, 100);
strokeWeight(2);
beginShape();
for (let v of trail) {
vertex(v.x, v.y);
}
endShape();
}
// Draw velocity and acceleration vectors at bob
function drawVectors(bx, by, angVel, angAcc, lenPx) {
// Velocity vector (tangential)
// v = angularVelocity * length (m/s)
let vMag = abs(angVel) * length; // m/s
// Scale velocity vector length for visualization
let vLen = map(vMag, 0, 5, 0, 80, true);
// Direction: perpendicular to rod, direction depends on sign of angular velocity
let vDir = angVel > 0 ? 1 : -1;
let vx = bx + vDir * vLen * cos(angle);
let vy = by - vDir * vLen * sin(angle);
stroke(50, 150, 50);
strokeWeight(3);
drawArrow(createVector(bx, by), createVector(vx, vy), 'Velocity');
// Acceleration vector (tangential)
// a = angularAcceleration * length (m/s^2)
let aMag = abs(angAcc) * length;
let aLen = map(aMag, 0, 20, 0, 80, true);
let aDir = angAcc > 0 ? 1 : -1;
let ax = bx + aDir * aLen * cos(angle);
let ay = by - aDir * aLen * sin(angle);
stroke(200, 100, 20);
strokeWeight(3);
drawArrow(createVector(bx, by), createVector(ax, ay), 'Accel');
}
// Helper to draw arrow from base to tip with label
function drawArrow(base, tip, label) {
push();
fill(strokeColor());
strokeWeight(3);
line(base.x, base.y, tip.x, tip.y);
// Arrowhead
let angleArrow = atan2(tip.y - base.y, tip.x - base.x);
push();
translate(tip.x, tip.y);
rotate(angleArrow);
let size = 7;
triangle(0, 0, -size, size / 2, -size, -size / 2);
pop();
pop();
}
// Reset simulation to current slider values
function resetSim() {
angle = angleSlider.value();
angularVelocity = 0;
angularAcceleration = 0;
trail = [];
isPaused = false;
}
// Toggle pause/play
function togglePause() {
isPaused = !isPaused;
}
// Mouse interaction: drag bob to set angle
let dragging = false;
function mousePressed() {
let pxPerMeter = 150;
let lenPx = length * pxPerMeter;
let bobX = originX + lenPx * sin(angle);
let bobY = originY + lenPx * cos(angle);
let bobRadius = map(mass, 0.1, 5, 15, 40);
let d = dist(mouseX, mouseY, bobX, bobY);
if (d < bobRadius + 5) {
dragging = true;
isPaused = true;
}
}
function mouseDragged() {
if (dragging) {
// Calculate angle from origin to mouse
let dx = mouseX - originX;
let dy = mouseY - originY;
let newAngle = atan2(dx, dy);
angle = newAngle;
angularVelocity = 0;
angleSlider.value(angle);
}
}
function mouseReleased() {
if (dragging) {
dragging = false;
isPaused = false;
}
}