javascript
let angleSlider, velocitySlider;
let angle = 45;
let velocity = 50;
let g = 9.8; // gravity in m/s² (scaled)
let t = 0;
let dt = 0.1; // time step
let path = [];
let launched = false;
let startX, startY;
let scaleFactor = 5; // scale to convert physics units to pixels
function setup() {
createCanvas(800, 400);
angleSlider = createSlider(0, 90, 45, 1);
angleSlider.position(20, 20);
velocitySlider = createSlider(10, 100, 50, 1);
velocitySlider.position(20, 50);
startX = 50;
startY = height - 50; // bottom-left corner with some margin
}
function draw() {
background(220);
// Draw ground
stroke(100);
line(0, startY, width, startY);
// Read controls
angle = angleSlider.value();
velocity = velocitySlider.value();
// Display controls labels
noStroke();
fill(0);
textSize(14);
text(`Angle: ${angle}°`, angleSlider.x * 2 + angleSlider.width, 35);
text(`Velocity: ${velocity} m/s`, velocitySlider.x * 2 + velocitySlider.width, 65);
if (!launched) {
// Draw projectile at start position
fill(255, 0, 0);
ellipse(startX, startY, 15, 15);
// Draw launch direction arrow
push();
translate(startX, startY);
stroke(0, 0, 255);
strokeWeight(2);
rotate(radians(-angle));
line(0, 0, velocity * scaleFactor * 0.1, 0);
fill(0, 0, 255);
triangle(velocity * scaleFactor * 0.1, 0, velocity * scaleFactor * 0.1 - 10, -5, velocity * scaleFactor * 0.1 - 10, 5);
pop();
fill(0);
text("Click to launch", width / 2 - 50, 30);
} else {
// Calculate position using projectile motion formulas
let rad = radians(angle);
let x = velocity * cos(rad) * t;
let y = velocity * sin(rad) * t - 0.5 * g * t * t;
// Convert physics coords to canvas coords
let px = startX + x * scaleFactor;
let py = startY - y * scaleFactor;
// Add current position to path
path.push(createVector(px, py));
// Draw trajectory path
noFill();
stroke(0, 150, 0);
beginShape();
for (let v of path) {
vertex(v.x, v.y);
}
endShape();
// Draw projectile
fill(255, 0, 0);
noStroke();
ellipse(px, py, 15, 15);
// Calculate velocity components at time t
let vx = velocity * cos(rad);
let vy = velocity * sin(rad) - g * t;
// Draw velocity vector
push();
stroke(0, 0, 255);
strokeWeight(2);
translate(px, py);
// Scale velocity vector for visualization
let vScale = 10;
line(0, 0, vx * vScale, -vy * vScale);
// Arrowhead
let arrowSize = 7;
let angleVec = atan2(-vy * vScale, vx * vScale);
translate(vx * vScale, -vy * vScale);
rotate(angleVec);
fill(0, 0, 255);
noStroke();
triangle(0, 0, -arrowSize, arrowSize / 2, -arrowSize, -arrowSize / 2);
pop();
// Update time
t += dt;
// Reset conditions: projectile hits ground or goes off screen
if (py > startY || px > width || py < 0) {
resetProjectile();
}
}
}
function mousePressed() {
// Launch projectile if clicked near start position and not already launched
if (!launched) {
let d = dist(mouseX, mouseY, startX, startY);
if (d < 50) {
launched = true;
t = 0;
path = [];
}
}
}
function resetProjectile() {
launched = false;
t = 0;
path = [];
}