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 PROJECTILE PHYSICS:
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('Projectile Physics', 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 projectile physics
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: projectile physics with WORKING controls, REALISTIC timing, and MINIMAL text displays
javascript
let canvasWidth = 600;
let canvasHeight = 400;
let gravitySlider, angleSlider, speedSlider, airSlider, massSlider, radiusSlider;
let resetBtn, pauseBtn, presetBtn1, presetBtn2;
let isPaused = false;
let g = 9.81; // m/s², gravity constant
let angle = 45; // degrees
let speed = 20; // m/s
let airResistance = 0.0; // drag coefficient (0 to 0.1)
let mass = 1; // kg
let radius = 0.1; // meters (for drag area and visualization)
let pos, vel, acc;
let timeElapsed = 0;
let trail = [];
let timeScale = 0.05; // seconds per frame approx
// Scaling: 1 meter = 15 pixels
let meterToPixel = 15;
// Ground level in pixels
let groundY;
function setup() {
createCanvas(canvasWidth, canvasHeight);
groundY = height - 50;
// Sliders with realistic ranges and defaults
angleSlider = createSlider(5, 85, 45, 1);
angleSlider.position(10, height + 10);
angleSlider.style('width', '120px');
speedSlider = createSlider(5, 50, 20, 0.1);
speedSlider.position(150, height + 10);
speedSlider.style('width', '120px');
airSlider = createSlider(0, 0.1, 0, 0.001);
airSlider.position(290, height + 10);
airSlider.style('width', '120px');
massSlider = createSlider(0.1, 10, 1, 0.1);
massSlider.position(430, height + 10);
massSlider.style('width', '120px');
radiusSlider = createSlider(0.05, 0.5, 0.1, 0.01);
radiusSlider.position(570, height + 10);
radiusSlider.style('width', '120px');
// Buttons
resetBtn = createButton('Reset');
resetBtn.position(10, height + 45);
resetBtn.mousePressed(resetSim);
pauseBtn = createButton('Pause/Play');
pauseBtn.position(80, height + 45);
pauseBtn.mousePressed(togglePause);
presetBtn1 = createButton('Preset: No Air');
presetBtn1.position(180, height + 45);
presetBtn1.mousePressed(presetNoAir);
presetBtn2 = createButton('Preset: High Drag');
presetBtn2.position(300, height + 45);
presetBtn2.mousePressed(presetHighDrag);
resetSim();
frameRate(60);
}
function draw() {
background(245);
drawGrid();
// Update parameters from sliders
angle = angleSlider.value();
speed = speedSlider.value();
airResistance = airSlider.value();
mass = massSlider.value();
radius = radiusSlider.value();
// Title
fill(30);
noStroke();
textAlign(CENTER, TOP);
textSize(22);
text('Projectile Physics', width / 2, 10);
// Parameter displays top-left corner
fill(50);
textSize(14);
textAlign(LEFT, TOP);
text('Angle: ' + angle.toFixed(0) + '°', 10, 40);
text('Speed: ' + speed.toFixed(1) + ' m/s', 10, 60);
text('Air Drag: ' + airResistance.toFixed(3), 10, 80);
text('Mass: ' + mass.toFixed(2) + ' kg', 10, 100);
text('Radius: ' + radius.toFixed(2) + ' m', 10, 120);
if (!isPaused) {
// Physics update with fixed timestep
updatePhysics();
}
drawGround();
drawProjectile();
drawVectors();
drawTrail();
}
function updatePhysics() {
// Convert angle to radians
let angleRad = radians(angle);
// Forces
// Gravity force vector
let Fg = createVector(0, mass * g);
// Velocity vector in m/s
// Drag force: Fd = 0.5 * airDensity * v^2 * Cd * A (simplified here)
// We'll approximate drag coefficient Cd ~ 0.47 (sphere)
// Air density ~ 1.225 kg/m³
// Area A = pi * r^2
let airDensity = 1.225;
let Cd = 0.47;
let area = PI * radius * radius;
let vMag = vel.mag();
let dragMag = 0.5 * airDensity * vMag * vMag * Cd * area * airResistance;
// Drag force direction opposite velocity
let Fd = vel.copy();
if (vMag > 0) {
Fd.mult(-dragMag / vMag);
} else {
Fd.set(0, 0);
}
// Total force
let Ftotal = p5.Vector.add(Fg, Fd);
// Acceleration = F/m
acc = p5.Vector.div(Ftotal, mass);
// Update velocity and position with timeScale
vel.add(p5.Vector.mult(acc, timeScale));
pos.add(p5.Vector.mult(vel, timeScale));
timeElapsed += timeScale;
// Add position to trail (limit length)
trail.push(pos.copy());
if (trail.length > 200) {
trail.shift();
}
// Stop if projectile hits ground
if (pos.y >= groundY / meterToPixel) {
pos.y = groundY / meterToPixel;
vel.set(0, 0);
acc.set(0, 0);
isPaused = true;
}
}
function drawProjectile() {
// Convert position meters to pixels
let px = pos.x * meterToPixel;
let py = groundY - pos.y * meterToPixel;
// Projectile circle
fill(200, 50, 50);
stroke(150, 0, 0);
strokeWeight(1.5);
ellipse(px, py, radius * 2 * meterToPixel, radius * 2 * meterToPixel);
}
function drawTrail() {
noFill();
stroke(150, 0, 0, 150);
strokeWeight(2);
beginShape();
for (let p of trail) {
let px = p.x * meterToPixel;
let py = groundY - p.y * meterToPixel;
vertex(px, py);
}
endShape();
}
function drawVectors() {
// Draw velocity vector at projectile
let px = pos.x * meterToPixel;
let py = groundY - pos.y * meterToPixel;
// Velocity vector scaled for visualization
let vScale = 10;
let vx = vel.x * vScale;
let vy = -vel.y * vScale;
stroke(50, 100, 200);
strokeWeight(3);
fill(50, 100, 200);
drawArrow(px, py, px + vx, py + vy);
// Acceleration vector scaled
let aScale = 100;
let ax = acc.x * aScale;
let ay = -acc.y * aScale;
stroke(50, 200, 100);
strokeWeight(3);
fill(50, 200, 100);
drawArrow(px, py, px + ax, py + ay);
}
function drawArrow(x1, y1, x2, y2) {
line(x1, y1, x2, y2);
push();
translate(x2, y2);
let angle = atan2(y1 - y2, x1 - x2);
rotate(angle);
triangle(0, 0, 8, 4, 8, -4);
pop();
}
function drawGround() {
stroke(100);
strokeWeight(1);
line(0, groundY, width, groundY);
// Draw horizontal grid lines every 2 meters
stroke(200);
strokeWeight(1);
for (let y = 0; y <= groundY; y += 2 * meterToPixel) {
line(0, groundY - y, width, groundY - y);
}
// Draw vertical grid lines every 5 meters
for (let x = 0; x <= width; x += 5 * meterToPixel) {
line(x, groundY, x, 0);
}
}
// Reset simulation to initial conditions
function resetSim() {
let angleRad = radians(angleSlider.value());
let initSpeed = speedSlider.value();
pos = createVector(0, 0);
vel = createVector(initSpeed * cos(angleRad), initSpeed * sin(angleRad));
acc = createVector(0, 0);
timeElapsed = 0;
trail = [];
isPaused = false;
}
// Pause/play toggle
function togglePause() {
isPaused = !isPaused;
}
// Preset: No Air Resistance
function presetNoAir() {
airSlider.value(0);
angleSlider.value(45);
speedSlider.value(25);
massSlider.value(1);
radiusSlider.value(0.1);
resetSim();
}
// Preset: High Drag
function presetHighDrag() {
airSlider.value(0.08);
angleSlider.value(60);
speedSlider.value(20);
massSlider.value(0.5);
radiusSlider.value(0.3);
resetSim();
}
// Mouse interaction: click and drag to set angle and speed visually
let dragging = false;
function mousePressed() {
if (
mouseX >= 0 &&
mouseX <= width &&
mouseY >= 0 &&
mouseY <= groundY
) {
dragging = true;
updateAngleSpeedFromMouse();
}
}
function mouseDragged() {
if (dragging) {
updateAngleSpeedFromMouse();
}
}
function mouseReleased() {
if (dragging) {
dragging = false;
resetSim();
}
}
function updateAngleSpeedFromMouse() {
// Vector from origin (bottom-left) to mouse
let dx = mouseX;
let dy = groundY - mouseY;
if (dx < 1) dx = 1; // avoid zero division
let angleDeg = degrees(atan2(dy, dx));
if (angleDeg < 0) angleDeg = 0;
if (angleDeg > 89) angleDeg = 89;
let distMeters = dist(0, groundY, mouseX, mouseY) / meterToPixel;
let speedVal = constrain(distMeters * 2, 5, 50); // scale speed by distance
angleSlider.value(angleDeg);
speedSlider.value(speedVal);
}