javascriptkhan-academy

How can i make a circular motion in javascript


I'm trying to make the Solar System using javascript, and I'm using khan academy to make it, but i don't know how can i make them move in a circle around the Sun I kept browsing the net for hours, but i couldn't find anything. Here's my project so that you can see what i have done and what can you do in it

https://www.khanacademy.org/computer-programming/solar-system/6120244512161792


Solution

  • Just to get you started:

    x = 100  // center
    y = 50   // center
    r = 50   // radius
    a = 0    // angle (from 0 to Math.PI * 2)
    
    function rotate(a) {
      
      var px = x + r * Math.cos(a); // <-- that's the maths you need
      var py = y + r * Math.sin(a);
      
      document.querySelector('#point').style.left = px + "px";
      document.querySelector('#point').style.top = py + "px";  
    }
    
    
    setInterval(function() {
      a = (a + Math.PI / 360) % (Math.PI * 2);
      rotate(a);
    }, 5);
    div {
      position: fixed;
      width: 10px;
      height: 10px;
    }
    
    #center {
      left: 100px;
      top: 50px;
      background: black;
    }
    
    #point {
      left: 0px;
      top: 0px;
      background: red;
    }
    <div id="center"></div>
    <div id="point"></div>