Adding more objects to orbit on Canvas

In the prevoius post you have learned how to make some object move in circular motion around given point on Canvas. Object in this case is simple circle image with radius = 20 pixels and blue color. It orbits around canvas center point. Since in given example canvas dimensions are 500 x 500 pixels, imaginery orbiting point for this blue circle is x = 250 and y = 250. Orbit distance is 100 pixels. 

Now, if you want to add another circle to orbit around same point, but at some different distance you can easily do so. Just above setInterval function definition add next two lines: 

// second object distance  
var radius2 = 150;  

This new radius2 variable will orbit new object slightly further from the first blue circle. Below these two lines add code to set second object angle and speed. 

// second object angle and speed  
var alpha2 = 0;  
var freq2 = 1/75;  

Next copy and paste below // draw object section, but change variable names to match second object variables. like so: 

// draw second object  
alpha2 += freq2;  
if(alpha2 >= 2*Math.PI)  
  alpha2 = 0;  
var object2X = center + (radius2 * Math.cos(alpha2));  
var object2Y = center + (radius2 * Math.sin(alpha2));  

As you can see from the last line, this new satellite will be green with 10 pixels radius. One other note, since we set frequency variable to 1/75, green circle will be slower than blue one. You can change this value to experiment further. 

If you repeat this process described above, you can add as many objects as you like with different colors, radius and speed. If you include black background and check Wikipedia or NASA for data on planets like distance from the Sun and color, you can easily simulate Solar system using this code. It will not be too precise since some planets have their own satellites. 

Next time you will learn how to include those satellites and make them part of the system. 


Post a Comment