So the red one is children of the blue one, when the blue one rotates, the red one too. But, the red one also have its own rotating speed. The problem is that the red one’s speed isn’t constant, probably because I am using 2 setInterval functions that are responsible for both rotating’s time… So, for example, each 2 seconds the blue moves 10 px and each 1 second the red moves 5px. Every odd second, red moves 5px. Every even second, red moves 15px. How can I keep it the same?
<!DOCTYPE html>
<html lang="en-US">
<head>
<link href="test.css" rel="stylesheet">
<title>Orbit</title>
</head>
<body>
<div class="box">
<div id="earth">
<div id="moon"></div>
</div>
</div>
<script>
r_moon = 100; // radius
r_earth = 200;
a = 0;
b = 0;
function rotate_moon(a)
{
var px_moon = r_moon * Math.cos(a);
var py_moon = r_moon * Math.sin(a);
document.querySelector('#moon').style.left = px_moon + "px";
document.querySelector('#moon').style.top = py_moon + "px";
}
function rotate_earth(b)
{
var px_earth = r_earth * Math.cos(b);
var py_earth = r_earth * Math.sin(b);
document.querySelector('#earth').style.left = px_earth + "px";
document.querySelector('#earth').style.top = py_earth + "px";
}
setInterval(function moon()
{
a = (a + Math.PI / 360) % (Math.PI * 2);
rotate_moon(a);
}, 10);
setInterval(function earth()
{
b = (b + Math.PI / 360) % (Math.PI * 2);
rotate_earth(b);
}, 50);
</script>
</body>
</html>
html
{
height: 100%; width: 100%;
}
body
{
margin: 0;
}
.box
{
margin: auto; margin-top: 200px;
height: 400px;
aspect-ratio: 1 / 1;
display: flex; justify-content: center; align-items: center;
}
#earth
{
position: relative;
height: 30px;
aspect-ratio: 1 / 1;
display: flex; justify-content: center; align-items: center;
background-color: blue;
}
#moon
{
position: relative;
height: 20px;
aspect-ratio: 1 / 1;
background-color: red;
}