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
let lengthSlider, massSlider, gravitySlider, dampingSlider, angleSlider, timeScaleSlider;
let length = 200; // Length of pendulum rod (pixels)
let mass = 1; // Mass (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 timeScale = 1; // Time scale multiplier
// Pendulum state variables
let angleVel = 0; // Angular velocity (rad/s)
let angleAcc = 0; // Angular acceleration (rad/s^2)
// Control buttons
let resetBtn, pauseBtn, presetBtn1, presetBtn2;
let isPaused = false;
// Physical scaling
// We map length in pixels to meters for physics calculations.
// Assume 1 pixel = 0.005 m (0.5 cm) for realistic scaling
const pixelToMeter = 0.005;
// For trail
let trail = [];
function setup() {
createCanvas(canvasSize, canvasSize);
frameRate(60);
// Sliders with realistic ranges and steps
lengthSlider = createSlider(50, 300, 200, 1); // length in pixels (10cm to 1.5m approx)
lengthSlider.position(10, height + 10);
lengthSlider.style('width', '150px');
massSlider = createSlider(0.1, 5, 1, 0.1); // mass in kg
massSlider.position(10, height + 40);
massSlider.style('width', '150px');
gravitySlider = createSlider(0.1, 20, 9.81, 0.1); // gravity m/s^2
gravitySlider.position(10, height + 70);
gravitySlider.style('width', '150px');
dampingSlider = createSlider(0.90, 1.00, 0.995, 0.001); // damping factor
dampingSlider.position(10, height + 100);
dampingSlider.style('width', '150px');
angleSlider = createSlider(0, 90, 45, 1); // initial angle degrees
angleSlider.position(10, height + 130);
angleSlider.style('width', '150px');
timeScaleSlider = createSlider(0.1, 3, 1, 0.01); // time scale multiplier
timeScaleSlider.position(10, height + 160);
timeScaleSlider.style('width', '150px');
// Buttons
resetBtn = createButton('Reset');
resetBtn.position(180, height + 10);
resetBtn.mousePressed(resetSim);
pauseBtn = createButton('Pause/Play');
pauseBtn.position(180, height + 40);
pauseBtn.mousePressed(togglePause);
presetBtn1 = createButton('Preset: Small Angle');
presetBtn1.position(180, height + 70);
presetBtn1.mousePressed(presetSmallAngle);
presetBtn2 = createButton('Preset: Heavy Mass');
presetBtn2.position(180, height + 100);
presetBtn2.mousePressed(presetHeavyMass);
resetSim();
}
function draw() {
background(245);
// Update parameters from sliders
length = lengthSlider.value();
mass = massSlider.value();
gravity = gravitySlider.value();
damping = dampingSlider.value();
timeScale = timeScaleSlider.value();
let initialAngleDeg = angleSlider.value();
// Show title
fill(30);
textAlign(CENTER, TOP);
textSize(20);
text('Pendulum Motion', width / 2, 10);
// Physics calculations
// Convert length to meters for physics
let L = length * pixelToMeter;
// Only update physics if not paused
if (!isPaused) {
// Angular acceleration: α = -(g/L) * sin(θ) - damping * ω
// Damping applied as multiplicative factor on velocity after integration
angleAcc = (-gravity / L) * sin(angle);
angleVel += angleAcc * (deltaTime / 1000) * timeScale;
angleVel *= damping;
angle += angleVel * (deltaTime / 1000) * timeScale;
}
// If user changes initial angle slider while paused, update angle accordingly
if (isPaused) {
angle = radians(initialAngleDeg);
angleVel = 0;
}
// Pendulum origin (pivot)
let originX = width / 2;
let originY = 80;
// Bob position
let bobX = originX + length * sin(angle);
let bobY = originY + length * cos(angle);
// Store trail points (limit length)
trail.push({ x: bobX, y: bobY });
if (trail.length > 150) trail.shift();
// Draw grid lines (every 50 pixels)
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);
}
// Draw pivot point
stroke(0);
strokeWeight(3);
fill(50);
ellipse(originX, originY, 12, 12);
// Draw rod
stroke(0, 100, 200);
strokeWeight(4);
line(originX, originY, bobX, bobY);
// Draw bob
fill(200, 50, 50);
stroke(150, 0, 0);
strokeWeight(2);
ellipse(bobX, bobY, mass * 15, mass * 15);
// Draw trail
noFill();
stroke(200, 50, 50, 100);
strokeWeight(2);
beginShape();
for (let p of trail) {
vertex(p.x, p.y);
}
endShape();
// Draw velocity vector (tangential)
// Velocity magnitude = L * angular velocity
let vMag = L * angleVel;
let vScale = 50; // scale for vector display
let vx = vScale * vMag * cos(angle + HALF_PI);
let vy = vScale * vMag * sin(angle + HALF_PI);
stroke(50, 150, 50);
strokeWeight(3);
fill(50, 150, 50);
push();
translate(bobX, bobY);
line(0, 0, vx, vy);
// Arrowhead
let arrowSize = 7;
let angleVec = atan2(vy, vx);
translate(vx, vy);
rotate(angleVec);
triangle(0, 0, -arrowSize, arrowSize / 2, -arrowSize, -arrowSize / 2);
pop();
// Draw acceleration vector (tangential)
// Acceleration magnitude = L * angular acceleration
let aMag = L * angleAcc;
let aScale = 150; // scale for vector display
let ax = aScale * aMag * cos(angle + HALF_PI);
let ay = aScale * aMag * sin(angle + HALF_PI);
stroke(50, 50, 200);
strokeWeight(3);
fill(50, 50, 200);
push();
translate(bobX, bobY);
line(0, 0, ax, ay);
// Arrowhead
let angleAccVec = atan2(ay, ax);
translate(ax, ay);
rotate(angleAccVec);
triangle(0, 0, -arrowSize, arrowSize / 2, -arrowSize, -arrowSize / 2);
pop();
// Display key parameters (minimal, neat)
noStroke();
fill(0);
textSize(14);
textAlign(LEFT, TOP);
// Velocity magnitude in m/s
let velocityMS = abs(vMag).toFixed(2);
// Acceleration magnitude in m/s^2
let accelMS2 = abs(aMag).toFixed(2);
// Angle in degrees
let angleDeg = degrees(angle) % 360;
if (angleDeg > 180) angleDeg -= 360; // Normalize between -180 and 180
text(`Angle: ${angleDeg.toFixed(1)}°`, 10, 30);
text(`Velocity: ${velocityMS} m/s`, 10, 50);
text(`Acceleration: ${accelMS2} m/s²`, 10, 70);
text(`Length: ${(L).toFixed(2)} m`, 10, 90);
text(`Mass: ${mass.toFixed(2)} kg`, 10, 110);
// Draw pivot reference line (vertical)
stroke(100, 100, 100, 100);
strokeWeight(1);
line(originX, originY, originX, originY + length + 20);
// Draw angle arc near pivot
noFill();
stroke(0, 0, 0, 100);
strokeWeight(2);
arc(originX, originY, 50, 50, 0, angle);
// Mouse interaction: drag bob to set angle (only when paused)
if (isPaused && mouseIsPressed) {
let dx = mouseX - originX;
let dy = mouseY - originY;
angle = atan2(dx, dy);
angleSlider.value(degrees(angle));
angleVel = 0;
trail = [];
}
}
// Reset simulation to slider initial values
function resetSim() {
angle = radians(angleSlider.value());
angleVel = 0;
trail = [];
isPaused = false;
}
// Toggle pause/play
function togglePause() {
isPaused = !isPaused;
if (isPaused) {
angleVel = 0; // freeze velocity when paused
}
}
// Preset: Small angle, low damping, normal gravity
function presetSmallAngle() {
lengthSlider.value(200);
massSlider.value(1);
gravitySlider.value(9.81);
dampingSlider.value(0.999);
angleSlider.value(10);
timeScaleSlider.value(1);
resetSim();
}
// Preset: Heavy mass, longer length, higher damping
function presetHeavyMass() {
lengthSlider.value(250);
massSlider.value(4);
gravitySlider.value(9.81);
dampingSlider.value(0.990);
angleSlider.value(60);
timeScaleSlider.value(1);
resetSim();
}