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, Educational
let canvasSize = 400;
// Pendulum physical parameters (controlled by sliders)
let lengthSlider, massSlider, gravitySlider, dampingSlider, angleSlider, timeScaleSlider;
let length = 200; // length in pixels (scaled)
let mass = 1; // mass in kg
let gravity = 9.81; // gravity m/s^2
let damping = 0.995; // damping factor (dimensionless)
let angle = Math.PI / 4; // initial angle (radians)
let timeScale = 1; // simulation speed multiplier
// Pendulum state variables
let theta; // current angle (rad)
let omega = 0; // angular velocity (rad/s)
let alpha = 0; // angular acceleration (rad/s^2)
let originX, originY;
let isPaused = false;
// Buttons
let resetBtn, pauseBtn, presetBtn1, presetBtn2;
function setup() {
createCanvas(canvasSize, canvasSize);
frameRate(60);
originX = width / 2;
originY = 80;
// Sliders with realistic ranges and steps
lengthSlider = createSlider(50, 300, 200, 1);
lengthSlider.position(10, height + 10);
lengthSlider.style('width', '120px');
massSlider = createSlider(0.1, 10, 1, 0.1);
massSlider.position(150, height + 10);
massSlider.style('width', '120px');
gravitySlider = createSlider(0.1, 20, 9.81, 0.1);
gravitySlider.position(290, height + 10);
gravitySlider.style('width', '120px');
dampingSlider = createSlider(0.90, 1.00, 0.995, 0.0005);
dampingSlider.position(10, height + 40);
dampingSlider.style('width', '120px');
angleSlider = createSlider(0, 90, 45, 1);
angleSlider.position(150, height + 40);
angleSlider.style('width', '120px');
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);
// Initialize pendulum state
resetSim();
}
function draw() {
background(245);
// Update parameters from sliders
length = lengthSlider.value();
mass = massSlider.value();
gravity = gravitySlider.value();
damping = dampingSlider.value();
timeScale = timeScaleSlider.value();
// Initial angle slider only affects initial condition on reset
// But allow live change to angle only if paused
if (isPaused) {
theta = radians(angleSlider.value());
omega = 0;
}
// Physics timestep (fixed timestep for stability)
let dt = (deltaTime / 1000) * timeScale; // seconds scaled by timeScale
dt = constrain(dt, 0, 0.05); // limit max dt to avoid instability
if (!isPaused) {
// Equation of motion for pendulum: alpha = -(g / L) * sin(theta) - damping * omega
alpha = (-gravity / (length / 100)) * sin(theta); // length converted to meters scale (100 px = 1 m)
omega += alpha * dt;
omega *= damping;
theta += omega * dt;
}
// Pendulum bob position
let bobX = originX + length * sin(theta);
let bobY = originY + length * cos(theta);
// Draw grid and axes
drawGrid();
// Draw pendulum arm
stroke(50);
strokeWeight(3);
line(originX, originY, bobX, bobY);
// Draw pivot
fill(0);
circle(originX, originY, 12);
// Draw bob with mass-based radius
let bobRadius = map(mass, 0.1, 10, 10, 30);
fill(70, 130, 180);
stroke(0);
strokeWeight(1);
circle(bobX, bobY, bobRadius * 2);
// Draw trail of bob (using history)
drawTrail(bobX, bobY);
// Draw velocity vector (tangential)
drawVelocityVector(bobX, bobY);
// Draw acceleration vector (tangential)
drawAccelerationVector(bobX, bobY);
// Display title
fill(0);
noStroke();
textAlign(CENTER, CENTER);
textSize(20);
text('Pendulum Motion', width / 2, 30);
// Display key parameters (top-left corner)
textSize(14);
textAlign(LEFT, TOP);
fill(0);
// Angular velocity in rad/s and converted to deg/s
let omegaDeg = degrees(omega);
text(`Angle: ${degrees(theta).toFixed(1)}°`, 10, 50);
text(`Angular Velocity: ${omega.toFixed(3)} rad/s`, 10, 70);
text(`Angular Accel.: ${alpha.toFixed(3)} rad/s²`, 10, 90);
text(`Length: ${(length / 100).toFixed(2)} m`, 10, 110);
text(`Gravity: ${gravity.toFixed(2)} m/s²`, 10, 130);
}
// Trail storage and drawing
let trail = [];
function drawTrail(x, y) {
trail.push(createVector(x, y));
if (trail.length > 100) trail.shift();
noFill();
stroke(70, 130, 180, 100);
strokeWeight(2);
beginShape();
for (let v of trail) {
vertex(v.x, v.y);
}
endShape();
}
// Draw velocity vector (tangential to arc, blue)
function drawVelocityVector(bobX, bobY) {
// Velocity magnitude in m/s: v = omega * L (L in meters)
let Lm = length / 100;
let v = omega * Lm;
// Direction: perpendicular to radius vector, tangent to circle
// Tangent vector components (normalized)
let tx = cos(theta);
let ty = -sin(theta);
// Scale vector for display
let scaleV = 50; // pixels per m/s
stroke(0, 0, 255);
strokeWeight(3);
fill(0, 0, 255, 150);
push();
translate(bobX, bobY);
line(0, 0, tx * v * scaleV, ty * v * scaleV);
// Arrowhead
let arrowSize = 7;
translate(tx * v * scaleV, ty * v * scaleV);
rotate(atan2(ty, tx));
triangle(0, 0, -arrowSize, arrowSize / 2, -arrowSize, -arrowSize / 2);
pop();
noStroke();
fill(0, 0, 255);
textAlign(LEFT, BOTTOM);
text(`Velocity: ${abs(v).toFixed(2)} m/s`, bobX + 10, bobY - 10);
}
// Draw acceleration vector (tangential component, red)
function drawAccelerationVector(bobX, bobY) {
// Tangential acceleration magnitude: a = alpha * L (L in meters)
let Lm = length / 100;
let a = alpha * Lm;
// Direction same as velocity vector but sign depends on alpha
let tx = cos(theta);
let ty = -sin(theta);
// Scale vector for display
let scaleA = 150; // pixels per m/s^2
stroke(255, 0, 0);
strokeWeight(3);
fill(255, 0, 0, 150);
push();
translate(bobX, bobY);
line(0, 0, tx * a * scaleA, ty * a * scaleA);
// Arrowhead
let arrowSize = 7;
translate(tx * a * scaleA, ty * a * scaleA);
rotate(atan2(ty, tx));
triangle(0, 0, -arrowSize, arrowSize / 2, -arrowSize, -arrowSize / 2);
pop();
noStroke();
fill(255, 0, 0);
textAlign(LEFT, TOP);
text(`Accel.: ${a.toFixed(2)} m/s²`, bobX + 10, bobY + 10);
}
// Draw subtle grid and reference lines
function drawGrid() {
stroke(200);
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);
}
// Draw horizontal reference line at pivot height
stroke(150);
strokeWeight(2);
line(0, originY, width, originY);
}
// Reset simulation to initial state
function resetSim() {
theta = radians(angleSlider.value());
omega = 0;
alpha = 0;
trail = [];
isPaused = false;
}
// Pause/play toggle
function togglePause() {
isPaused = !isPaused;
}
// Preset: Small angle (approx linear)
function presetSmallAngle() {
lengthSlider.value(200);
massSlider.value(1);
gravitySlider.value(9.81);
dampingSlider.value(0.995);
angleSlider.value(10);
timeScaleSlider.value(1);
resetSim();
}
// Preset: Large angle (nonlinear)
function presetLargeAngle() {
lengthSlider.value(150);
massSlider.value(2);
gravitySlider.value(9.81);
dampingSlider.value(0.99);
angleSlider.value(75);
timeScaleSlider.value(1);
resetSim();
}