Branchwell

Watch Encyclopedia / website / exp / orbits.js

1WE.mount('orbits', function (S) {
2 var C = S.C, ctx = S.ctx, GM = 398600, RE = 6371, R0 = RE + 800, shots = [], msg = 'Pick a speed and fire. Too slow and it falls. Fast enough and it never comes down.';
3 var v = S.slider('Launch speed', 0, 11.5, 7.9, .1, function (x) { return x.toFixed(1) + ' km/s'; });
4 S.button('Fire', function () { shots.push({ x: 0, y: R0, vx: v.v, vy: 0, tr: [], done: false, v: v.v, t: 0, ang: 0 }); if (shots.length > 6) shots.shift(); });
5 shots.push({ x: 0, y: R0, vx: 7.9, vy: 0, tr: [], done: false, v: 7.9, t: 0, ang: 0 });
6 S.button('Clear', function () { shots = []; });
7 S.loop(function (dt) {
8 S.clear(); var w = S.W, h = S.H, sc = Math.min(w, h) / (RE * 5.2), cx = w / 2, cy = h * .56;
9 shots.forEach(function (s) {
10 if (s.done) return;
11 for (var i = 0; i < 60; i++) { var r = Math.hypot(s.x, s.y), a = -GM / (r * r * r), st = 4; s.vx += a * s.x * st; s.vy += a * s.y * st; s.x += s.vx * st; s.y += s.vy * st; s.t += st; if (i % 6 === 0) s.tr.push([s.x, s.y]);
12 var r2 = Math.hypot(s.x, s.y), an = Math.atan2(s.x, s.y); if (an < 0) an += S.TAU; if (an < s.ang - 3) { s.done = true; var sa = 1 / (2 / R0 - s.v * s.v / GM), T = S.TAU * Math.sqrt(sa * sa * sa / GM) / 60; msg = '<b>Orbit.</b> At ' + s.v.toFixed(1) + ' km/s it keeps missing the ground. One lap takes ' + (T < 180 ? T.toFixed(0) + ' minutes' : (T / 60).toFixed(1) + ' hours') + '.'; break; } s.ang = an;
13 if (r2 < RE) { s.done = true; msg = '<b>It fell back</b> after ' + Math.round(an * RE).toLocaleString() + ' km along the ground. Try a little faster.'; break; }
14 if (r2 > RE * 9) { s.done = true; msg = s.v * s.v / 2 - GM / R0 >= 0 ? '<b>Escape.</b> At ' + s.v.toFixed(1) + ' km/s it leaves the Earth for good.' : '<b>A long, stretched orbit.</b> It swings far out before the Earth pulls it back.'; break; } }
15 if (s.tr.length > 4000) s.tr.splice(0, 500);
16 });
17 var g = ctx.createRadialGradient(cx - RE * sc * .3, cy - RE * sc * .3, RE * sc * .2, cx, cy, RE * sc); g.addColorStop(0, '#3f86c4'); g.addColorStop(1, '#14324f'); ctx.fillStyle = g; ctx.beginPath(); ctx.arc(cx, cy, RE * sc, 0, S.TAU); ctx.fill(); S.ring(cx, cy, RE * sc + 3, 'rgba(111,177,230,.3)', 4);
18 ctx.fillStyle = C.mut; ctx.beginPath(); ctx.moveTo(cx - 7, cy - RE * sc + 1); ctx.lineTo(cx, cy - R0 * sc); ctx.lineTo(cx + 7, cy - RE * sc + 1); ctx.fill();
19 var vc = Math.sqrt(GM / R0); S.arrow(cx, cy - R0 * sc, cx + 14 + v.v * 7, cy - R0 * sc, C.acc, 2);
20 shots.forEach(function (s, i) { ctx.beginPath(); s.tr.forEach(function (p) { ctx.lineTo(cx + p[0] * sc, cy - p[1] * sc); }); ctx.strokeStyle = [C.acc, C.blue, C.green, C.pink, C.violet, C.teal][i % 6]; ctx.lineWidth = 1.6; ctx.stroke(); if (!s.done) S.dot(cx + s.x * sc, cy - s.y * sc, 4, C.ink); });
21 S.txt('Circular orbit here needs ' + vc.toFixed(1) + ' km/s. Escape needs ' + (vc * Math.SQRT2).toFixed(1) + ' km/s.', 14, 20, C.mut, 12.5);
22 S.say(msg);
23 });
24});