JSFiddle - React, Tailwind, and code Playground
HTML
<div>
<button id="pause">
Pause
</button>
<button id="friction">
Enable friction
</button>
</div>
<svg height="600" width="600">
<circle id="planet" cx="5" cy="300" r="4" stroke="black" stroke-width="1" fill="cyan" />
<circle id="sun" cx="300" cy="300" r="30" stroke="black" stroke-width="1" fill="yellow" />
</svg>
JavaScript
//Initial position and speed
planet_x = 5;
planet_y = 300;
planet_xspeed = 0;
planet_yspeed = 20;
sun_x = 300;
sun_y = 300;
planetObj = $('#planet')[0];
function update() {
//update position of planet according to its speed
planet_x += planet_xspeed * 0.02;
planet_y += planet_yspeed * 0.02;
//work out distance from planet to sun
x_dist = sun_x - planet_x;
y_dist = sun_y - planet_y;
dist = Math.sqrt(x_dist*x_dist + y_dist*y_dist);
//According to Newton's Law of Gravitation,
//the acceleration due to gravity of one body towards another
//is proportional to 1 over the square of the distance
acceleration = 10000 / (dist * dist);
//the acceleration happens towards the sun
//so we find the x and y components like this:
acceleration_x = acceleration * x_dist / dist;
acceleration_y = acceleration * y_dist / dist;
//update planet's speed based on sun's gravity
planet_xspeed += acceleration_x;
planet_yspeed += acceleration_y;
if (friction) {
planet_xspeed = 0.999 * planet_xspeed;
planet_yspeed = 0.999 * planet_yspeed;
}
//makes the new position visible
planetObj.cx.baseVal.value = planet_x;
planetObj.cy.baseVal.value = planet_y;
}
//this sets up the buttons
var friction;
var updater;
fr_on = function() {
friction = true;
$('#friction').html('Disable friction');
$('#friction').on('click', fr_off);
}
fr_off = function () {
friction = false;
$('#friction').html('Enable friction');
$('#friction').on('click', fr_on);
}
fr_off();
pause = function() {
clearInterval(updater);
$('#pause').html('Unpause');
$('#pause').off('click');
$('#pause').on('click', unpause);
}
unpause = function () {
updater = setInterval(update, 20);
$('#pause').html('Pause');
$('#pause').off('click');
$('#pause').on('click', pause);
}
unpause();