main.js entry 2.5 KB
Copy main.js
SimKit.define({
title: "Projectile with air drag",
dt: 1 / 600, speed: 1, height: 340,
params: {
v0: { label: "Launch speed", unit: "m/s", min: 5, max: 60, value: 30, step: 0.5 },
ang: { label: "Launch angle", unit: "°", min: 5, max: 85, value: 45, step: 1 },
k: { label: "Drag coefficient", unit: "1/m", min: 0, max: 0.05, value: 0.01, step: 0.001 },
h0: { label: "Launch height", unit: "m", min: 0, max: 30, value: 0, step: 0.5 }
},
init(P, S) {
const a = P.ang * Math.PI / 180;
S.y = [0, P.h0, P.v0 * Math.cos(a), P.v0 * Math.sin(a)];
S.trail = [[0, P.h0]]; S.done = false; S.range = 0; S.maxH = P.h0;
},
step(dt, P, S, t) {
if (S.done) return;
S.y = SimKit.rk4((tt, s) => { const sp = Math.hypot(s[2], s[3]); return [s[2], s[3], -P.k * sp * s[2], -9.81 - P.k * sp * s[3]]; }, t, S.y, dt);
S.maxH = Math.max(S.maxH, S.y[1]);
if (S.trail.length < 1 || Math.hypot(S.y[0] - S.trail[S.trail.length - 1][0], S.y[1] - S.trail[S.trail.length - 1][1]) > 0.3) S.trail.push([S.y[0], S.y[1]]);
if (S.y[1] <= 0) { S.done = true; S.range = S.y[0]; S.y[1] = 0; S.trail.push([S.y[0], 0]); }
},
draw(g, W, H, P, S) {
const a = P.ang * Math.PI / 180, vac = (P.v0 * Math.cos(a) / 9.81) * (P.v0 * Math.sin(a) + Math.sqrt(P.v0 * P.v0 * Math.sin(a) ** 2 + 2 * 9.81 * P.h0));
const xmax = Math.max(vac * 1.05, S.y[0] * 1.1, 10), ymax = Math.max(S.maxH * 1.3, P.v0 * P.v0 * Math.sin(a) ** 2 / (2 * 9.81) * 1.2 + P.h0, 5);
const sx = (W - 60) / xmax, sy = (H - 50) / ymax, X = x => 30 + x * sx, Y = y => H - 25 - y * sy;
g.strokeStyle = "#888"; g.lineWidth = 1; g.beginPath(); g.moveTo(20, Y(0)); g.lineTo(W - 10, Y(0)); g.stroke();
g.strokeStyle = "#9bb"; g.setLineDash([5, 5]); g.beginPath();
for (let x = 0; x <= vac; x += vac / 60) { const yy = P.h0 + x * Math.tan(a) - 9.81 * x * x / (2 * (P.v0 * Math.cos(a)) ** 2); g[x === 0 ? "moveTo" : "lineTo"](X(x), Y(yy)); }
g.stroke(); g.setLineDash([]);
g.strokeStyle = "#2a5fd0"; g.lineWidth = 2.5; g.beginPath(); S.trail.forEach((p, i) => g[i ? "lineTo" : "moveTo"](X(p[0]), Y(p[1]))); g.stroke();
g.fillStyle = "#c03030"; g.beginPath(); g.arc(X(S.y[0]), Y(S.y[1]), 7, 0, 2 * Math.PI); g.fill();
SimKit.sch.label(g, "range " + S.y[0].toFixed(1) + " m, max height " + S.maxH.toFixed(1) + " m (dashed: without drag)", W / 2, 16, "#444");
},
scope: {
span: 6, unit: "",
traces: [
{ label: "Height (m)", color: "#5aa0ff", get: S => S.y[1] },
{ label: "Speed (m/s)", color: "#ff9a40", get: S => Math.hypot(S.y[2], S.y[3]) }
]
}
});