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 canvasW = 600;
let canvasH = 400;
// Pendulum physical parameters (controlled by sliders)
let lengthSlider, massSlider, gravitySlider, angleSlider, dampingSlider, timeScaleSlider;
let length = 200; // meters scaled to pixels
let mass = 1; // kg
let gravity = 9.81; // m/s^2
let angle = Math.PI / 4; // radians (initial angle)
let damping = 0.995; // dimensionless damping coefficient
let timeScale = 1; // real-time multiplier
// Pendulum state variables
let theta; // current angle (rad)
let omega = 0; // angular velocity (rad/s)
let alpha = 0; // angular acceleration (rad/s^2)
// Control buttons
let resetBtn, pauseBtn, presetBtn1, presetBtn2;
let isPaused = false;
// For mouse interaction
let draggingBob = false;
let bobX, bobY;
function setup() {
createCanvas(canvasW, canvasH);
frameRate(60);
// Sliders with realistic ranges and steps
lengthSlider = createSlider(50, 300, 200, 1); // length in pixels ~ meters
lengthSlider.position(10, height + 10);
lengthSlider.style('width', '140px');
massSlider = createSlider(0.1, 5, 1, 0.1); // mass in kg
massSlider.position(170, height + 10);
massSlider.style('width', '140px');
gravitySlider = createSlider(1, 20, 9.81, 0.01); // gravity m/s^2
gravitySlider.position(330, height + 10);
gravitySlider.style('width', '140px');
angleSlider = createSlider(0, 90, 45, 1); // initial angle degrees
angleSlider.position(10, height + 40);
angleSlider.style('width', '140px');
dampingSlider = createSlider(0.9, 1, 0.995, 0.0005); // damping factor
dampingSlider.position(170, height + 40);
dampingSlider.style('width', '140px');
timeScaleSlider = createSlider(0.1, 3, 1, 0.01); // time scale multiplier
timeScaleSlider.position(330, height + 40);
timeScaleSlider.style('width', '140px');
// Buttons
resetBtn = createButton('Reset');
resetBtn.position(490, height + 10);
resetBtn.mousePressed(resetSim);
pauseBtn = createButton('Pause/Play');
pauseBtn.position(490, height + 40);
pauseBtn.mousePressed(togglePause);
presetBtn1 = createButton('Preset: Small Angle');
presetBtn1.position(10, height + 70);
presetBtn1.mousePressed(() => {
lengthSlider.value(200);
massSlider.value(1);
gravitySlider.value(9.81);
angleSlider.value(10);
dampingSlider.value(0.995);
timeScaleSlider.value(1);
resetSim();
});
presetBtn2 = createButton('Preset: Large Angle');
presetBtn2.position(150, height + 70);
presetBtn2.mousePressed(() => {
lengthSlider.value(150);
massSlider.value(2);
gravitySlider.value(9.81);
angleSlider.value(75);
dampingSlider.value(0.99);
timeScaleSlider.value(1);
resetSim();
});
// 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 in radians from degrees slider (only on reset)
// angleSlider controls initial angle only, so update theta only if paused or just reset
if (isPaused || frameCount === 1) {
theta = radians(angleSlider.value());
omega = 0;
}
// Physics update if not paused and not dragging bob
if (!isPaused && !draggingBob) {
// Equation of motion: alpha = -(g / L) * sin(theta) - damping * omega
// Using simple damping proportional to velocity
alpha = (-gravity / length) * sin(theta);
omega += alpha * (deltaTime / 1000) * timeScale;
omega *= damping;
theta += omega * (deltaTime / 1000) * timeScale;
}
// Bob position
let originX = width / 2;
let originY = 80;
bobX = originX + length * sin(theta);
bobY = originY + length * cos(theta);
// If dragging bob, update angle based on mouse position
if (draggingBob) {
let dx = mouseX - originX;
let dy = mouseY - originY;
theta = atan2(dx, dy);
omega = 0; // reset velocity while dragging
}
// Draw grid lines for reference
drawGrid();
// Draw pendulum arm
stroke(50);
strokeWeight(3);
line(originX, originY, bobX, bobY);
// Draw pivot
fill(0);
noStroke();
ellipse(originX, originY, 12, 12);
// Draw bob with mass-dependent size
let bobRadius = map(mass, 0.1, 5, 12, 30);
fill(70, 130, 180);
stroke(0);
strokeWeight(1.5);
ellipse(bobX, bobY, bobRadius * 2, bobRadius * 2);
// Draw trail of bob (simple fading trail)
drawTrail();
// Draw velocity vector (tangential)
drawVelocityVector(originX, originY, bobX, bobY, theta, omega);
// Draw acceleration vector (tangential)
drawAccelerationVector(originX, originY, bobX, bobY, theta, alpha);
// Display title
fill(30);
noStroke();
textAlign(CENTER, TOP);
textSize(22);
text('Pendulum Motion', width / 2, 10);
// Display parameters (minimal, neat)
fill(30);
textSize(14);
textAlign(LEFT, TOP);
let vx = omega * length * cos(theta + HALF_PI);
let vy = omega * length * sin(theta + HALF_PI);
let velocityMag = sqrt(vx * vx + vy * vy);
text('Length: ' + length + ' px', 10, 40);
text('Mass: ' + mass.toFixed(2) + ' kg', 10, 60);
text('Gravity: ' + gravity.toFixed(2) + ' m/s²', 10, 80);
text('Angle: ' + degrees(theta).toFixed(1) + '°', width - 160, 40);
text('Angular Vel: ' + omega.toFixed(3) + ' rad/s', width - 160, 60);
text('Angular Acc: ' + alpha.toFixed(3) + ' rad/s²', width - 160, 80);
// Draw slider labels below canvas
drawSliderLabels();
}
function drawGrid() {
stroke(200);
strokeWeight(1);
for (let y = 100; y < height; y += 50) {
line(0, y, width, y);
}
for (let x = 0; x < width; x += 50) {
line(x, 100, x, height);
}
}
let trail = [];
function drawTrail() {
trail.push({ x: bobX, y: bobY });
if (trail.length > 60) trail.shift();
noFill();
stroke(70, 130, 180, 100);
strokeWeight(2);
beginShape();
for (let i = 0; i < trail.length; i++) {
let p = trail[i];
vertex(p.x, p.y);
}
endShape();
}
function drawVelocityVector(ox, oy, bx, by, angle, omega) {
// Tangential velocity vector at bob position
let vMag = abs(omega * length);
if (vMag < 0.01) return; // skip if too small
// Direction perpendicular to radius vector (tangential)
let vx = vMag * cos(angle + HALF_PI);
let vy = vMag * sin(angle + HALF_PI);
// Scale vector for display
let scaleV = 50;
stroke(220, 50, 50);
strokeWeight(3);
fill(220, 50, 50);
push();
translate(bx, by);
line(0, 0, vx * scaleV, vy * scaleV);
// Arrowhead
let arrowSize = 7;
push();
translate(vx * scaleV, vy * scaleV);
rotate(atan2(vy, vx));
triangle(0, 0, -arrowSize, arrowSize / 2, -arrowSize, -arrowSize / 2);
pop();
pop();
noStroke();
fill(220, 50, 50);
textSize(12);
textAlign(LEFT, CENTER);
text('v', bx + vx * scaleV + 5, by + vy * scaleV);
}
function drawAccelerationVector(ox, oy, bx, by, angle, alpha) {
// Tangential acceleration vector at bob position
let aMag = abs(alpha * length);
if (aMag < 0.01) return; // skip if too small
// Direction perpendicular to radius vector (tangential)
let ax = aMag * cos(angle + HALF_PI) * (alpha < 0 ? -1 : 1);
let ay = aMag * sin(angle + HALF_PI) * (alpha < 0 ? -1 : 1);
// Scale vector for display
let scaleA = 150;
stroke(50, 150, 50);
strokeWeight(3);
fill(50, 150, 50);
push();
translate(bx, by);
line(0, 0, ax * scaleA, ay * scaleA);
// Arrowhead
let arrowSize = 7;
push();
translate(ax * scaleA, ay * scaleA);
rotate(atan2(ay, ax));
triangle(0, 0, -arrowSize, arrowSize / 2, -arrowSize, -arrowSize / 2);
pop();
pop();
noStroke();
fill(50, 150, 50);
textSize(12);
textAlign(LEFT, CENTER);
text('a', bx + ax * scaleA + 5, by + ay * scaleA);
}
function drawSliderLabels() {
fill(0);
noStroke();
textSize(12);
textAlign(LEFT, CENTER);
text('Length (px)', lengthSlider.x * 1, lengthSlider.y - 10);
text('Mass (kg)', massSlider.x * 1, massSlider.y - 10);
text('Gravity (m/s²)', gravitySlider.x * 1, gravitySlider.y - 10);
text('Init Angle (°)', angleSlider.x * 1, angleSlider.y - 10);
text('Damping', dampingSlider.x * 1, dampingSlider.y - 10);
text('Time Scale', timeScaleSlider.x * 1, timeScaleSlider.y - 10);
}
function resetSim() {
theta = radians(angleSlider.value());
omega = 0;
alpha = 0;
trail = [];
isPaused = false;
}
function togglePause() {
isPaused = !isPaused;
}
function mousePressed() {
// Check if mouse is near bob to start dragging
let d = dist(mouseX, mouseY, bobX, bobY);
let bobRadius = map(mass, 0.1, 5, 12, 30);
if (d < bobRadius + 10) {
draggingBob = true;
isPaused = true;
}
}
function mouseReleased() {
if (draggingBob) {
draggingBob = false;
omega = 0;
isPaused = false;
}
}