Create a complete, interactive p5.js sketch based on these detailed specifications:…
- User
Create a complete, interactive p5.js sketch based on these detailed specifications:
json - Assistant
Create a complete, interactive p5.js sketch based on these detailed specifications:
{
"SIMULATION": "Projectile Motion Interactive Simulation",
"DESCRIPTION": "This simulation demonstrates projectile motion with adjustable launch angle, initial velocity, gravity, and air resistance. Users can observe the trajectory of a projectile and analyze its range, maximum height, and time of flight. The simulation includes visual aids like trajectory lines and range markers.",
"CONTROLS": [
{
"type": "slider",
"parameter": "launchAngle",
"label": "Launch Angle (°)",
"min": 0,
"max": 90,
"default": 45,
"step": 1,
"description": "Adjusts the initial launch angle of the projectile in degrees."
},
{
"type": "slider",
"parameter": "initialVelocity",
"label": "Initial Velocity (m/s)",
"min": 5,
"max": 50,
"default": 25,
"step": 1,
"description": "Adjusts the initial velocity of the projectile in meters per second."
},
{
"type": "slider",
"parameter": "gravity",
"label": "Gravity (m/s²)",
"min": 0.1,
"max": 20,
"default": 9.81,
"step": 0.1,
"description": "Adjusts the acceleration due to gravity."
},
{
"type": "slider",
"parameter": "airResistance",
"label": "Air Resistance (Drag Coefficient)",
"min": 0.0,
"max": 0.2,
"default": 0.0,
"step": 0.01,
"description": "Adjusts the air resistance coefficient (drag). 0 means no air resistance."
},
{
"type": "button",
"label": "Launch",
"function": "launchProjectile",
"description": "Launches the projectile with the current settings."
},
{
"type": "button",
"label": "Reset",
"function": "resetSimulation",
"description": "Resets the projectile to its initial position and clears the trajectory."
},
{
"type": "button",
"label": "Toggle Trail",
"function": "toggleTrail",
"description": "Toggles the display of the projectile's trajectory trail."
}
],
"VISUALS": {
"projectile": {
"shape": "circle",
"size": 15,
"color": "red",
"x": "initialX",
"y": "initialY",
"description": "Represents the projectile being launched."
},
"ground": {
"shape": "rectangle",
"x": 0,
"y": "groundLevel",
"width": "canvasWidth",
"height": 20,
"color": "green",
"description": "Represents the ground."
},
"trajectory": {
"type": "line",
"color": "rgba(0, 0, 255, 0.5)",
"thickness": 2,
"points": "trajectoryPoints",
"visibility": "showTrail",
"description": "A line showing the projectile's path. `trajectoryPoints` is an array of {x,y} points. `showTrail` is a boolean."
},
"rangeMarker": {
"type": "line",
"color": "black",
"thickness": 1,
"x1": "range",
"y1": "groundLevel",
"x2": "range",
"y2": "groundLevel - 10",
"description": "A line indicating the range of the projectile."
},
"textDisplay": [
{
"label": "Range: ",
"variable": "range",
"x": 20,
"y": 30,
"color": "black",
"description": "Displays the range of the projectile."
},
{
"label": "Max Height: ",
"variable": "maxHeight",
"x": 20,
"y": 50,
"color": "black",
"description": "Displays the maximum height achieved by the projectile."
},
{
"label": "Time of Flight: ",
"variable": "timeOfFlight",
"x": 20,
"y": 70,
"color": "black",
"description": "Displays the total time the projectile is in the air."
}
]
},
"PHYSICS": {
"variables": [
"initialX",
"initialY",
"velocityX",
"velocityY",
"currentTime",
"x",
"y",
"range",
"maxHeight",
"timeOfFlight",
"launched",
"groundLevel",
"trajectoryPoints",
"showTrail"
],
"initialConditions": {
"initialX": 50,
"initialY": 450,
"currentTime": 0,
"x": "initialX",
"y": "initialY",
"range": 0,
"maxHeight": 0,
"timeOfFlight": 0,
"launched": false,
"groundLevel": 470,
"trajectoryPoints": "[]",
"showTrail": true
},
"equations": [
"velocityX = initialVelocity * cos(radians(launchAngle))",
"velocityY = initialVelocity * sin(radians(launchAngle))",
"x = initialX + velocityX * currentTime",
"y = initialY - (velocityY * currentTime - 0.5 * gravity * currentTime * currentTime)",
"airResistanceForceX = -0.5 * airResistance * velocityX * velocityX * sign(velocityX)",
"airResistanceForceY = -0.5 * airResistance * velocityY * velocityY * sign(velocityY)",
"accelerationX = airResistanceForceX / projectileMass", // projectileMass needs to be defined (e.g., 1)
"accelerationY = -gravity + (airResistanceForceY / projectileMass)",
"velocityX = velocityX + accelerationX * deltaTime", // Need to introduce deltaTime for frame-based calculation
"velocityY = velocityY + accelerationY * deltaTime" // Need to introduce deltaTime for frame-based calculation
],
"calculations": [
"range = x - initialX",
"maxHeight = initialY - Math.min(...trajectoryPoints.map(p => p.y)) if trajectoryPoints is not empty, otherwise zero.",
"timeOfFlight = currentTime"
],
"collisionDetection": {
"condition": "y >= groundLevel",
"action": "launched = false; y = groundLevel; timeOfFlight = currentTime;"
},
"deltaTime": 0.02 // Simulation timestep. Smaller values are more accurate but slower.
},
"INTERACTIONS": {
"mouse": {
"click": "N/A - Launch button triggers action",
"move": "N/A"
},
"keyboard": {
"keys": {
"SPACE": "If not launched, call `launchProjectile`",
"R": "Call `resetSimulation`"
}
},
"launchProjectile": {
"description": "Launches the projectile with current settings. Sets `launched` to true, resets `currentTime`, `x`, `y` and clears the `trajectoryPoints` array.",
"action": "launched = true; currentTime = 0; x = initialX; y = initialY; trajectoryPoints = [];"
},
"resetSimulation": {
"description": "Resets the projectile to its initial position and state.",
"action": "launched = false; currentTime = 0; x = initialX; y = initialY; range = 0; maxHeight = 0; timeOfFlight = 0; trajectoryPoints = [];"
},
"toggleTrail": {
"description": "Toggles the display of the trajectory trail.",
"action": "showTrail = !showTrail"
},
"simulationUpdate": {
"description": "Updates the projectile's position and other parameters each frame.",
"condition": "launched",
"actions": [
"currentTime += deltaTime",
"Update velocityX and velocityY based on airResistance force calculations.",
"x = initialX + velocityX * currentTime",
"y = initialY - (velocityY * currentTime - 0.5 * gravity * currentTime * currentTime)",
"trajectoryPoints.push({x: x, y: y})",
"if (y >= groundLevel) { collisionDetection.action }",
"Calculate range, maxHeight and timeOfFlight based on the updated positions and flight history."
]
}
}
}
Requirements:
IMPORTANT: Only output the JavaScript code, no explanations or markdown formatting. The code should be self-contained and runnable in the p5.js editor with all interactive controls working.
let launchAngleSlider, initialVelocitySlider, gravitySlider, airResistanceSlider; let launchButton, resetButton, toggleTrailButton;
let initialX = 50; let initialY = 350; // Adjusted to fit canvas height 400 with ground at 370 let groundLevel = 370;
let x, y; let velocityX, velocityY; let currentTime = 0; let deltaTime = 0.02; // seconds per simulation step let projectileMass = 1; // arbitrary mass for air resistance calculation
let launched = false; let trajectoryPoints = []; let showTrail = true;
let range = 0; let maxHeight = 0; let timeOfFlight = 0;
function setup() { createCanvas(400, 400); textFont('Arial'); // Create sliders with labels and descriptions
// Launch Angle Slider (0-90 degrees) launchAngleSlider = createSlider(0, 90, 45, 1); launchAngleSlider.position(20, height + 10); launchAngleSlider.style('width', '150px');
// Initial Velocity Slider (5-50 m/s) initialVelocitySlider = createSlider(5, 50, 25, 1); initialVelocitySlider.position(20, height + 40); initialVelocitySlider.style('width', '150px');
// Gravity Slider (0.1 - 20 m/s^2) gravitySlider = createSlider(0.1, 20, 9.81, 0.1); gravitySlider.position(20, height + 70); gravitySlider.style('width', '150px');
// Air Resistance Slider (0.0 - 0.2) airResistanceSlider = createSlider(0.0, 0.2, 0.0, 0.01); airResistanceSlider.position(20, height + 100); airResistanceSlider.style('width', '150px');
// Buttons launchButton = createButton('Launch'); launchButton.position(200, height + 10); launchButton.mousePressed(launchProjectile); launchButton.attribute('title', 'Launches the projectile with the current settings.');
resetButton = createButton('Reset'); resetButton.position(200, height + 40); resetButton.mousePressed(resetSimulation); resetButton.attribute('title', 'Resets the projectile to its initial position and clears the trajectory.');
toggleTrailButton = createButton('Toggle Trail'); toggleTrailButton.position(200, height + 70); toggleTrailButton.mousePressed(toggleTrail); toggleTrailButton.attribute('title', "Toggles the display of the projectile's trajectory trail.");
// Initialize projectile position resetSimulation(); }
function draw() { background(240);
// Draw ground noStroke(); fill(34, 139, 34); // green color rect(0, groundLevel, width, height - groundLevel);
// Draw controls labels and descriptions fill(0); noStroke(); textSize(12); textStyle(BOLD);
text('Launch Angle (°): ' + launchAngleSlider.value(), launchAngleSlider.x * 1 + launchAngleSlider.width + 10, launchAngleSlider.y + 15); text('Adjusts the initial launch angle of the projectile in degrees.', launchAngleSlider.x * 1 + launchAngleSlider.width + 10, launchAngleSlider.y + 30);
text('Initial Velocity (m/s): ' + initialVelocitySlider.value(), initialVelocitySlider.x * 1 + initialVelocitySlider.width + 10, initialVelocitySlider.y + 15); text('Adjusts the initial velocity of the projectile in meters per second.', initialVelocitySlider.x * 1 + initialVelocitySlider.width + 10, initialVelocitySlider.y + 30);
text('Gravity (m/s²): ' + gravitySlider.value().toFixed(2), gravitySlider.x * 1 + gravitySlider.width + 10, gravitySlider.y + 15); text('Adjusts the acceleration due to gravity.', gravitySlider.x * 1 + gravitySlider.width + 10, gravitySlider.y + 30);
text('Air Resistance (Drag Coefficient): ' + airResistanceSlider.value().toFixed(2), airResistanceSlider.x * 1 + airResistanceSlider.width + 10, airResistanceSlider.y + 15); text('Adjusts the air resistance coefficient (drag). 0 means no air resistance.', airResistanceSlider.x * 1 + airResistanceSlider.width + 10, airResistanceSlider.y + 30);
// Update simulation if launched if (launched) { updateSimulation(); }
// Draw trajectory line if enabled if (showTrail && trajectoryPoints.length > 1) { stroke(0, 0, 255, 128); strokeWeight(2); noFill(); beginShape(); for (let p of trajectoryPoints) { vertex(p.x, p.y); } endShape(); }
// Draw projectile fill(255, 0, 0); stroke(150, 0, 0); strokeWeight(1); ellipse(x, y, 15, 15);
// Draw range marker line stroke(0); strokeWeight(1); line(initialX + range, groundLevel, initialX + range, groundLevel - 10);
// Draw text display for range, max height, time of flight noStroke(); fill(0); textSize(14); textStyle(BOLD); text('Range: ' + range.toFixed(2) + ' m', 20, 30); text('Max Height: ' + maxHeight.toFixed(2) + ' m', 20, 50); text('Time of Flight: ' + timeOfFlight.toFixed(2) + ' s', 20, 70);
// Draw axis labels and ground line stroke(0); strokeWeight(1); line(0, groundLevel, width, groundLevel); noStroke(); fill(0); textSize(12); text('Ground', 5, groundLevel - 5);
// Draw origin marker fill(0); ellipse(initialX, groundLevel, 5, 5); text('Launch Point', initialX + 5, groundLevel - 10); }
// Launch projectile with current settings function launchProjectile() { if (!launched) { launched = true; currentTime = 0; x = initialX; y = initialY; trajectoryPoints = [];
let angleRad = radians(launchAngleSlider.value());
let v0 = initialVelocitySlider.value();
velocityX = v0 * cos(angleRad);
velocityY = v0 * sin(angleRad);
range = 0;
maxHeight = 0;
timeOfFlight = 0;
} }
// Reset simulation to initial state function resetSimulation() { launched = false; currentTime = 0; x = initialX; y = initialY; velocityX = 0; velocityY = 0; range = 0; maxHeight = 0; timeOfFlight = 0; trajectoryPoints = []; }
// Toggle the trajectory trail display function toggleTrail() { showTrail = !showTrail; }
// Update simulation physics and positions function updateSimulation() { // Increment time by deltaTime currentTime += deltaTime;
let gravity = gravitySlider.value(); let airResistance = airResistanceSlider.value();
// Calculate air resistance forces // Air resistance force formula: Fd = -0.5 * Cd * v^2 * sign(v) // Here, Cd is airResistance coefficient, v is velocity component
// sign function helper function sign(n) { return n >= 0 ? 1 : -1; }
// Calculate drag forces on velocity components let airResistanceForceX = -0.5 * airResistance * velocityX * velocityX * sign(velocityX); let airResistanceForceY = -0.5 * airResistance * velocityY * velocityY * sign(velocityY);
// Calculate accelerations let accelerationX = airResistanceForceX / projectileMass; let accelerationY = -gravity + (airResistanceForceY / projectileMass);
// Update velocities using Euler integration velocityX += accelerationX * deltaTime; velocityY += accelerationY * deltaTime;
// Update positions x += velocityX * deltaTime * 50; // scale factor for visualization y -= velocityY * deltaTime * 50; // y axis inverted in canvas, so subtract
// Add current position to trajectory points trajectoryPoints.push({x: x, y: y});
// Collision detection with ground if (y >= groundLevel) { y = groundLevel; launched = false; timeOfFlight = currentTime; }
// Calculate range (horizontal distance from initialX) range = x - initialX;
// Calculate max height (vertical distance from initialY) if (trajectoryPoints.length > 0) { let minY = Math.min(...trajectoryPoints.map(p => p.y)); maxHeight = (initialY - minY) / 50; // convert back to meters (inverse of scale factor) } else { maxHeight = 0; }
// Update time of flight while flying if (launched) { timeOfFlight = currentTime; } }
// Keyboard interactions function keyPressed() { if (key === ' ' || key === 'Spacebar') { if (!launched) { launchProjectile(); } } if (key === 'r' || key === 'R') { resetSimulation(); } }