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
let canvasSize = 400;
// Pendulum physical parameters (controlled by sliders)
let lengthSlider, massSlider, gravitySlider, dampingSlider, angleSlider, timeScaleSlider;
let length = 200; // meters scaled (will scale visually)
let mass = 1; // kg
let gravity = 9.81; // m/s²
let damping = 0.995; // dimensionless damping factor
let initialAngle = Math.PI / 4; // radians (~45°)
let timeScale = 1; // real time multiplier
// Pendulum state variables
let angle; // current angle (radians)
let angularVelocity; // angular velocity (rad/s)
let angularAcceleration; // angular acceleration (rad/s²)
// Control buttons
let resetBtn, pauseBtn, presetBtn1, presetBtn2;
let isPaused = false;
function setup() {
createCanvas(canvasSize, canvasSize);
// Sliders with realistic ranges and defaults
lengthSlider = createSlider(50, 300, 200, 1); // length in pixels (scaled meters)
lengthSlider.position(10, height + 10);
lengthSlider.style('width', '120px');
massSlider = createSlider(0.1, 5, 1, 0.1); // mass in kg
massSlider.position(150, height + 10);
massSlider.style('width', '120px');
gravitySlider = createSlider(0.1, 20, 9.81, 0.01); // gravity m/s²
gravitySlider.position(290, height + 10);
gravitySlider.style('width', '120px');
dampingSlider = createSlider(0.90, 1.00, 0.995, 0.0005); // damping factor
dampingSlider.position(10, height + 40);
dampingSlider.style('width', '120px');
angleSlider = createSlider(0, 90, 45, 1); // initial angle degrees
angleSlider.position(150, height + 40);
angleSlider.style('width', '120px');
timeScaleSlider = createSlider(0.1, 3, 1, 0.01); // time scale multiplier
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(190, height + 75);
presetBtn1.mousePressed(() => {
lengthSlider.value(200);
massSlider.value(1);
gravitySlider.value(9.81);
dampingSlider.value(0.995);
angleSlider.value(10);
timeScaleSlider.value(1);
resetSim();
});
presetBtn2 = createButton('Preset: Large Angle');
presetBtn2.position(320, height + 75);
presetBtn2.mousePressed(() => {
lengthSlider.value(150);
massSlider.value(2);
gravitySlider.value(9.81);
dampingSlider.value(0.990);
angleSlider.value(80);
timeScaleSlider.value(1);
resetSim();
});
// Initialize pendulum state
resetSim();
frameRate(60);
}
function draw() {
background(245);
// Update parameters from sliders
length = lengthSlider.value();
mass = massSlider.value();
gravity = gravitySlider.value();
damping = dampingSlider.value();
initialAngle = radians(angleSlider.value());
timeScale = timeScaleSlider.value();
// Title
fill(30);
noStroke();
textAlign(CENTER, CENTER);
textSize(22);
text('Pendulum', width / 2, 25);
// Physics update if not paused
if (!isPaused) {
// Use fixed timestep for stability (dt in seconds)
let dt = (deltaTime / 1000) * timeScale;
if (dt > 0.05) dt = 0.05; // clamp max dt for stability
// Pendulum equation: angular acceleration = -(g / L) * sin(theta) - damping * angularVelocity
angularAcceleration = (-gravity / (length / 100)) * sin(angle);
angularVelocity += angularAcceleration * dt;
angularVelocity *= damping;
angle += angularVelocity * dt;
}
// Origin point (pivot)
let originX = width / 2;
let originY = 80;
// Pendulum bob position
let bobX = originX + length * sin(angle);
let bobY = originY + length * cos(angle);
// Draw grid lines for reference (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(2);
fill(50);
ellipse(originX, originY, 12, 12);
// Draw rod
stroke(50, 100, 200);
strokeWeight(4);
line(originX, originY, bobX, bobY);
// Draw bob
fill(200, 50, 50);
stroke(120, 0, 0);
strokeWeight(2);
ellipse(bobX, bobY, mass * 20, mass * 20);
// Draw trail of bob (store last positions)
drawTrail(bobX, bobY);
// Draw velocity vector (tangential)
drawVelocityVector(originX, originY, bobX, bobY);
// Draw acceleration vector (tangential)
drawAccelerationVector(originX, originY, bobX, bobY);
// Draw length measurement line and label
stroke(0, 150, 0);
strokeWeight(1);
line(originX, originY, originX, originY + length);
noStroke();
fill(0, 150, 0);
textAlign(LEFT, CENTER);
textSize(12);
text('L: ' + (length / 100).toFixed(2) + ' m', originX + 5, originY + length / 2);
// Display key parameters top-left corner
fill(0);
noStroke();
textAlign(LEFT, TOP);
textSize(14);
// Angular velocity in rad/s and deg/s
let angVelDeg = degrees(angularVelocity);
// Angular acceleration in rad/s² and deg/s²
let angAccDeg = degrees(angularAcceleration);
text('Angle: ' + degrees(angle).toFixed(1) + '°', 10, 40);
text('Angular Vel: ' + angVelDeg.toFixed(2) + ' °/s', 10, 60);
text('Angular Acc: ' + angAccDeg.toFixed(2) + ' °/s²', 10, 80);
text('Force (tangential): ' + (mass * gravity * sin(angle)).toFixed(2) + ' N', 10, 100);
text('Time Scale: ' + timeScale.toFixed(2) + 'x', 10, 120);
// Display slider values bottom-left corner
fill(0);
textSize(12);
textAlign(LEFT, BOTTOM);
text('Length (pixels): ' + length, 10, height - 10);
text('Mass (kg): ' + mass.toFixed(2), 10, height - 25);
text('Gravity (m/s²): ' + gravity.toFixed(2), 10, height - 40);
text('Damping: ' + damping.toFixed(3), 10, height - 55);
text('Init Angle (°): ' + angleSlider.value(), 10, height - 70);
text('Time Scale: ' + timeScale.toFixed(2), 10, height - 85);
}
// Trail storage and drawing
let trail = [];
const maxTrailLength = 80;
function drawTrail(x, y) {
trail.push(createVector(x, y));
if (trail.length > maxTrailLength) {
trail.shift();
}
noFill();
stroke(200, 50, 50, 150);
strokeWeight(2);
beginShape();
for (let v of trail) {
vertex(v.x, v.y);
}
endShape();
}
// Draw velocity vector (tangential to arc, scaled)
function drawVelocityVector(ox, oy, bx, by) {
// Velocity vector direction is perpendicular to rod, direction of angular velocity
let velMag = angularVelocity * (length / 100); // linear velocity magnitude (m/s)
let dir = angularVelocity > 0 ? 1 : -1;
// Unit vector perpendicular to rod (tangential)
let dx = bx - ox;
let dy = by - oy;
let len = sqrt(dx * dx + dy * dy);
let ux = -dy / len;
let uy = dx / len;
// Vector scaled for display
let scale = 50;
stroke(0, 0, 255);
strokeWeight(3);
fill(0, 0, 255);
push();
translate(bx, by);
line(0, 0, ux * velMag * scale * dir, uy * velMag * scale * dir);
// Arrowhead
let arrowSize = 7;
let vx = ux * velMag * scale * dir;
let vy = uy * velMag * scale * dir;
translate(vx, vy);
rotate(atan2(vy, vx));
triangle(0, 0, -arrowSize, arrowSize / 2, -arrowSize, -arrowSize / 2);
pop();
noStroke();
textSize(12);
fill(0, 0, 255);
textAlign(LEFT, BOTTOM);
text('v', bx + ux * velMag * scale * dir + 5, by + uy * velMag * scale * dir + 5);
}
// Draw acceleration vector (tangential to arc, scaled)
function drawAccelerationVector(ox, oy, bx, by) {
// Tangential acceleration magnitude = angularAcceleration * length
let accMag = abs(angularAcceleration) * (length / 100); // m/s²
let dir = angularAcceleration > 0 ? 1 : -1;
// Unit vector perpendicular to rod (tangential)
let dx = bx - ox;
let dy = by - oy;
let len = sqrt(dx * dx + dy * dy);
let ux = -dy / len;
let uy = dx / len;
// Vector scaled for display
let scale = 100;
stroke(0, 150, 0);
strokeWeight(3);
fill(0, 150, 0);
push();
translate(bx, by);
line(0, 0, ux * accMag * scale * dir, uy * accMag * scale * dir);
// Arrowhead
let arrowSize = 7;
let vx = ux * accMag * scale * dir;
let vy = uy * accMag * scale * dir;
translate(vx, vy);
rotate(atan2(vy, vx));
triangle(0, 0, -arrowSize, arrowSize / 2, -arrowSize, -arrowSize / 2);
pop();
noStroke();
textSize(12);
fill(0, 150, 0);
textAlign(LEFT, TOP);
text('a', bx + ux * accMag * scale * dir + 5, by + uy * accMag * scale * dir - 15);
}
// Reset simulation to initial state
function resetSim() {
angle = initialAngle;
angularVelocity = 0;
angularAcceleration = 0;
trail = [];
isPaused = false;
}
// Pause/play toggle
function togglePause() {
isPaused = !isPaused;
}
// Mouse interaction: drag bob to set angle (physically meaningful)
let dragging = false;
function mousePressed() {
let originX = width / 2;
let originY = 80;
let bobX = originX + length * sin(angle);
let bobY = originY + length * cos(angle);
let d = dist(mouseX, mouseY, bobX, bobY);
if (d < mass * 15) {
dragging = true;
isPaused = true; // pause while dragging
}
}
function mouseDragged() {
if (dragging) {
let originX = width / 2;
let originY = 80;
let dx = mouseX - originX;
let dy = mouseY - originY;
angle = atan2(dx, dy); // atan2(x,y) because y-axis is down
angularVelocity = 0;
trail = [];
}
}
function mouseReleased() {
if (dragging) {
dragging = false;
isPaused = false;
}
}