Create a complete, highly interactive p5.js simulation demonstrating: gravity simulation of a ball falling on earth surface
CRITICAL REQUIREMENTS:
ACCURACY: The simulation must be scientifically/mathematically accurate for gravity simulation of a ball falling on earth surface
FUNCTIONAL INTERACTIVITY: All sliders and buttons MUST actually control and modify the simulation behavior in real-time
EDUCATIONAL: Users should learn about gravity simulation of a ball falling on earth surface through experimentation and parameter manipulation
VISUAL PRECISION: Animations should be smooth, realistic, and visually accurate to real-world physics
MANDATORY INTERACTIVE ELEMENTS THAT MUST WORK:
At least 4-6 sliders controlling key parameters with realistic ranges - these MUST change simulation behavior
At least 3-4 buttons for actions (reset, pause/play, presets, etc.) - these MUST perform actual functions
Real-time parameter display showing current values that update as sliders move
Visual feedback that responds immediately and visibly to control changes
Mouse interactions where physically meaningful
CRITICAL: CONTROLS MUST BE FUNCTIONAL, NOT DECORATIVE
Every slider must control a variable that actively affects the simulation
Every button must perform a meaningful action that changes the simulation state
Parameter changes must be immediately visible in the simulation output
Use the actual slider values in mathematical calculations and physics equations
ANIMATION AND TIMING REQUIREMENTS:
Use realistic time scaling - avoid animations that are too fast or unrealistic
Implement proper frame rate control using deltaTime or fixed timesteps
Use realistic physical constants and scaling factors
Ensure smooth, stable animations at 60fps
Avoid conflicting visual elements or overlapping controls
Make animations visually appealing and scientifically accurate
CONTROL IMPLEMENTATION REQUIREMENTS:
Sliders: Use createSlider(min, max, default, step) with appropriate ranges that make physical sense
Buttons: Use createButton('Label') with meaningful functions that actually execute
Position controls below canvas using .parent(controlsDiv) and CSS for layout. ABSOLUTELY DO NOT use .position(x, y) for any p5.js elements (sliders, buttons, canvas) as this will break layout.
Show parameter values with text() in the main canvas that update in real-time
Use function declarations for event handlers: function resetSim() {}
ALWAYS use slider.value() in your calculations - never ignore slider inputs
Assistant
CODE FORMAT REQUIREMENTS:
Use GLOBAL MODE p5.js (NOT instance mode)
Define setup() and draw() as regular functions
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 GRAVITY SIMULATION OF A BALL FALLING ON EARTH SURFACE:
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 a div to hold all controls
let controlsDiv = createDiv('');
controlsDiv.id('p5-controls'); // Assign an ID for easier styling/selection
controlsDiv.style('display', 'flex');
controlsDiv.style('flex-wrap', 'wrap');
controlsDiv.style('gap', '10px'); // Spacing between controls
controlsDiv.style('margin-top', '10px'); // Space below canvas
// Create sliders that CONTROL the simulation with realistic ranges
gravitySlider = createSlider(0.1, 1.0, 0.4, 0.05);
gravitySlider.parent(controlsDiv); // Attach to the div
dampingSlider = createSlider(0.9, 1.0, 0.995, 0.001);
dampingSlider.parent(controlsDiv); // Attach to the div
// Create buttons that DO something
resetBtn = createButton('Reset');
resetBtn.parent(controlsDiv); // Attach to the div
pauseBtn = createButton('Pause/Play');
pauseBtn.parent(controlsDiv); // Attach to the div
// IMPORTANT: Ensure the canvas is also parented correctly if needed, or its container is styled.
// p5.js canvas is usually appended to the element where new p5.js(sketch, node) is called.
// The controlsDiv will be a sibling to the canvas within that parent node.
}
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('Gravity Simulation Of A Ball Falling On Earth Surface', 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 gravity simulation of a ball falling on earth surface
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: gravity simulation of a ball falling on earth surface with WORKING controls, REALISTIC timing, and MINIMAL text displays
javascript
// Global variables for physics and controls
let canvasSize = 400;
let ball; // object to hold ball state
// Physical constants and parameters controlled by sliders
let massSlider, heightSlider, airDensitySlider, dragCoeffSlider, gravitySlider, timeScaleSlider;
let resetBtn, pauseBtn, presetBtn1, presetBtn2;
let isPaused = false;
let controlsDiv;
function setup() {
createCanvas(canvasSize, canvasSize);
// Create controls container div below canvas
controlsDiv = createDiv('');
controlsDiv.id('p5-controls');
controlsDiv.style('display', 'flex');
controlsDiv.style('flex-wrap', 'wrap');
controlsDiv.style('gap', '15px');
controlsDiv.style('margin-top', '12px');
controlsDiv.style('justify-content', 'center');
controlsDiv.style('max-width', canvasSize + 'px');
// Mass slider (kg): 0.1 to 10 kg, default 1 kg
massSlider = createSlider(0.1, 10, 1, 0.1);
massSlider.parent(controlsDiv);
massSlider.style('width', '120px');
// Initial height slider (m): 1 to 100 m, default 50 m
heightSlider = createSlider(1, 100, 50, 1);
heightSlider.parent(controlsDiv);
heightSlider.style('width', '120px');
// Air density slider (kg/m^3): 0 to 1.3, default 1.225 (sea level)
airDensitySlider = createSlider(0, 1.3, 1.225, 0.01);
airDensitySlider.parent(controlsDiv);
airDensitySlider.style('width', '120px');
// Drag coefficient slider (dimensionless): 0 to 2, default 0.47 (sphere)
dragCoeffSlider = createSlider(0, 2, 0.47, 0.01);
dragCoeffSlider.parent(controlsDiv);
dragCoeffSlider.style('width', '120px');
// Gravity slider (m/s^2): 0 to 20, default 9.81
gravitySlider = createSlider(0, 20, 9.81, 0.01);
gravitySlider.parent(controlsDiv);
gravitySlider.style('width', '120px');
// Time scale slider (real time multiplier): 0.1 to 3, default 1
timeScaleSlider = createSlider(0.1, 3, 1, 0.01);
timeScaleSlider.parent(controlsDiv);
timeScaleSlider.style('width', '120px');
// Buttons
resetBtn = createButton('Reset');
resetBtn.parent(controlsDiv);
resetBtn.mousePressed(resetSimulation);
pauseBtn = createButton('Pause/Play');
pauseBtn.parent(controlsDiv);
pauseBtn.mousePressed(togglePause);
presetBtn1 = createButton('Preset: Earth Sea Level');
presetBtn1.parent(controlsDiv);
presetBtn1.mousePressed(() => {
massSlider.value(1);
heightSlider.value(50);
airDensitySlider.value(1.225);
dragCoeffSlider.value(0.47);
gravitySlider.value(9.81);
timeScaleSlider.value(1);
resetSimulation();
});
presetBtn2 = createButton('Preset: Moon Gravity');
presetBtn2.parent(controlsDiv);
presetBtn2.mousePressed(() => {
massSlider.value(1);
heightSlider.value(50);
airDensitySlider.value(0); // no atmosphere on moon
dragCoeffSlider.value(0);
gravitySlider.value(1.62);
timeScaleSlider.value(1);
resetSimulation();
});
// Initialize ball state
resetSimulation();
}
function draw() {
background(245);
// Draw ground line
stroke(100);
strokeWeight(2);
line(0, height - 40, width, height - 40);
// Draw grid lines for height reference (every 10m)
stroke(200);
strokeWeight(1);
for (let h = 10; h <= 100; h += 10) {
let y = map(h, 0, 100, height - 40, 40);
line(0, y, width, y);
}
noStroke();
// Read slider values (must use .value())
let mass = massSlider.value(); // kg
let initHeight = heightSlider.value(); // m
let airDensity = airDensitySlider.value(); // kg/m^3
let dragCoeff = dragCoeffSlider.value(); // dimensionless
let gravity = gravitySlider.value(); // m/s^2
let timeScale = timeScaleSlider.value(); // multiplier
// Update ball parameters if sliders changed (mass, drag, etc)
ball.mass = mass;
ball.dragCoeff = dragCoeff;
ball.airDensity = airDensity;
ball.gravity = gravity;
ball.timeScale = timeScale;
// Time step in seconds, scaled by timeScale and deltaTime
// deltaTime is ms since last frame
let dt = (deltaTime / 1000) * timeScale;
if (!isPaused) {
ball.update(dt);
}
// Draw ball at scaled position
// Map height (m) to y coordinate (pixels)
// 0 m = ground line (height - 40), max height = 100 m = 40 px from top
let yPos = map(ball.position, 0, 100, height - 40, 40);
yPos = constrain(yPos, 40, height - 40);
// Draw trail
ball.drawTrail();
// Draw ball
fill(50, 120, 220);
stroke(0);
strokeWeight(1);
ellipse(width / 2, yPos, 30, 30);
// Draw velocity vector (blue arrow)
let velLen = map(abs(ball.velocity), 0, 50, 0, 100);
stroke(0, 102, 204);
strokeWeight(3);
push();
translate(width / 2, yPos);
if (ball.velocity < 0) {
// Upward velocity arrow
line(0, 0, 0, -velLen);
line(0, -velLen, -5, -velLen + 10);
line(0, -velLen, 5, -velLen + 10);
} else {
// Downward velocity arrow
line(0, 0, 0, velLen);
line(0, velLen, -5, velLen - 10);
line(0, velLen, 5, velLen - 10);
}
pop();
// Draw acceleration vector (red arrow)
let accLen = map(abs(ball.acceleration), 0, 50, 0, 100);
stroke(204, 0, 0);
strokeWeight(3);
push();
translate(width / 2 + 40, yPos);
if (ball.acceleration < 0) {
// Upward acceleration arrow
line(0, 0, 0, -accLen);
line(0, -accLen, -5, -accLen + 10);
line(0, -accLen, 5, -accLen + 10);
} else {
// Downward acceleration arrow
line(0, 0, 0, accLen);
line(0, accLen, -5, accLen - 10);
line(0, accLen, 5, accLen - 10);
}
pop();
// Draw force vector (green arrow)
let forceLen = map(abs(ball.force), 0, 500, 0, 100);
stroke(0, 153, 0);
strokeWeight(3);
push();
translate(width / 2 - 40, yPos);
if (ball.force < 0) {
// Upward force arrow
line(0, 0, 0, -forceLen);
line(0, -forceLen, -5, -forceLen + 10);
line(0, -forceLen, 5, -forceLen + 10);
} else {
// Downward force arrow
line(0, 0, 0, forceLen);
line(0, forceLen, -5, forceLen - 10);
line(0, forceLen, 5, forceLen - 10);
}
pop();
// Title
fill(0);
noStroke();
textAlign(CENTER, TOP);
textSize(16);
text('Gravity Simulation Of A Ball Falling On Earth Surface', width / 2, 10);
// Display parameters (top-left corner)
textAlign(LEFT, TOP);
textSize(12);
fill(0);
noStroke();
// Velocity in m/s
text('Velocity: ' + ball.velocity.toFixed(2) + ' m/s', 10, 30);
// Acceleration in m/s²
text('Acceleration: ' + ball.acceleration.toFixed(2) + ' m/s²', 10, 50);
// Force in N
text('Force: ' + ball.force.toFixed(2) + ' N', 10, 70);
// Height in m
text('Height: ' + ball.position.toFixed(2) + ' m', 10, 90);
// Time scale multiplier
text('Time Scale: ' + timeScale.toFixed(2) + 'x', 10, 110);
// Display slider labels and values below each slider
displaySliderLabels();
}
// Ball object with physics state and methods
class Ball {
constructor() {
this.position = 50; // m, height above ground
this.velocity = 0; // m/s, positive downward
this.acceleration = 0; // m/s^2
this.mass = 1; // kg
this.dragCoeff = 0.47; // dimensionless
this.airDensity = 1.225; // kg/m^3
this.gravity = 9.81; // m/s^2
this.radius = 0.1; // m (10 cm radius ball)
this.area = PI * this.radius * this.radius; // cross-sectional area m^2
this.force = 0; // net force N
this.timeScale = 1;
this.trail = [];
this.maxTrailLength = 60;
}
update(dt) {
if (this.position <= 0 && this.velocity >= 0) {
// Ball on ground, apply damping to velocity to simulate bounce loss
this.position = 0;
this.velocity = 0;
this.acceleration = 0;
this.force = 0;
this.trail = [];
return;
}
// Calculate forces
// Gravity force downward (positive direction)
let Fg = this.mass * this.gravity;
// Drag force opposite velocity direction: Fd = 0.5 * rho * v^2 * Cd * A
// velocity sign matters for drag direction
let v = this.velocity;
let dragMag = 0.5 * this.airDensity * v * v * this.dragCoeff * this.area;
let Fd = -Math.sign(v) * dragMag;
// Net force
this.force = Fg + Fd;
// Acceleration a = F/m
this.acceleration = this.force / this.mass;
// Update velocity and position using Euler integration
this.velocity += this.acceleration * dt;
this.position += this.velocity * dt;
// Prevent going below ground
if (this.position < 0) {
this.position = 0;
this.velocity = 0;
this.acceleration = 0;
this.force = 0;
}
// Update trail for visualization
this.trail.push(this.position);
if (this.trail.length > this.maxTrailLength) {
this.trail.shift();
}
}
drawTrail() {
noFill();
stroke(50, 100, 200, 150);
strokeWeight(2);
beginShape();
for (let i = 0; i < this.trail.length; i++) {
let y = map(this.trail[i], 0, 100, height - 40, 40);
vertex(width / 2 - this.trail.length + i, y);
}
endShape();
}
}
function resetSimulation() {
ball = new Ball();
ball.position = heightSlider.value();
ball.mass = massSlider.value();
ball.airDensity = airDensitySlider.value();
ball.dragCoeff = dragCoeffSlider.value();
ball.gravity = gravitySlider.value();
ball.timeScale = timeScaleSlider.value();
ball.velocity = 0;
ball.acceleration = 0;
ball.force = 0;
ball.trail = [];
isPaused = false;
}
function togglePause() {
isPaused = !isPaused;
}
function displaySliderLabels() {
// Display labels and values below sliders in controlsDiv
// The controlsDiv children order:
// massSlider, heightSlider, airDensitySlider, dragCoeffSlider, gravitySlider, timeScaleSlider, resetBtn, pauseBtn, presetBtn1, presetBtn2
let labels = [
'Mass (kg): ',
'Initial Height (m): ',
'Air Density (kg/m³): ',
'Drag Coeff.: ',
'Gravity (m/s²): ',
'Time Scale (x): ',
];
let sliders = [
massSlider,
heightSlider,
airDensitySlider,
dragCoeffSlider,
gravitySlider,
timeScaleSlider,
];
// Remove previous label divs if any
let existingLabels = selectAll('.slider-label');
for (let lbl of existingLabels) {
lbl.remove();
}
// Create label divs below each slider
for (let i = 0; i < sliders.length; i++) {
let val = sliders[i].value();
let textVal;
if (i === 2) {
// air density with 3 decimals
textVal = val.toFixed(3);
} else if (i === 3) {
// drag coeff 2 decimals
textVal = val.toFixed(2);
} else if (i === 4) {
// gravity 2 decimals
textVal = val.toFixed(2);
} else if (i === 5) {
// time scale 2 decimals
textVal = val.toFixed(2);
} else {
// others 1 decimal
textVal = val.toFixed(1);
}
let labelDiv = createDiv(labels[i] + textVal);
labelDiv.class('slider-label');
labelDiv.style('font-size', '12px');
labelDiv.style('text-align', 'center');
labelDiv.style('width', '120px');
labelDiv.style('margin-top', '-6px');
labelDiv.parent(controlsDiv);
}
}
// Mouse interaction: click on ball to reset velocity to zero (simulate catch)
function mousePressed() {
let yPos = map(ball.position, 0, 100, height - 40, 40);
let d = dist(mouseX, mouseY, width / 2, yPos);
if (d < 15) {
ball.velocity = 0;
ball.acceleration = 0;
ball.force = 0;
ball.trail = [];
}
}