Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the position of an orbiting object

I'm creating a solar system animation using canvas and have a problem calculating an object's position (x,y) values.

Earth is orbiting around the Sun, and I need to calculate and update the Earth's position at each frame. And using Earth's position, I'll orbit the Moon around the Earth.

The related function is this:

orbitAround : function (master) {
    master.makeOrbitCenter();
    this.increaseOrbitAngle();
    context.rotate(this.orbit.angle * Math.PI/180);
    context.translate(this.orbit.distance, 0);

    // calculate and update the X and Y position of the earth
    // so that luna can orbit around earth
    // these are the initial values of earth
    this.position.x = master.position.x + this.orbit.distance;
    this.position.y = master.position.y;
},

Fiddle demo

To make it simpler, I've drawn this picture

enter image description here

Let's say the blue disc is the Earth, and is located at (300,200). The Sun is at (200,200) and the distance between them is 100. After the Earth makes a 45 degree rotation around the Sun, what would its position be? How can I calculate it using the given values?

like image 903
akinuri Avatar asked Dec 25 '22 21:12

akinuri


1 Answers

It looks like you've got something working there, but here's a breakdown:

Math.cos and Math.sin return a theoretical x and y position along an axis. They need to be given the angle in radians.

So, in order to get the position of a 45 degree angle, you essentially need to calculate the radian equivalent of degrees first.

var degrees = 45;
var radians = degrees * (Math.PI / 180);

The result here is 0.785398163. You can then get the x and y coordinate of the orbiting object using this:

var x = Math.cos(0.785398163) * distance;
var y = Math.sin(0.785398163) * distance;

The whole process for a single frame would look like this:

var distance = 100; // from the centre of orbit
var degrees = 45; // around a 360 degree orbit
var radians = degrees * (Math.PI / 180);

var x = Math.cos(radians) * distance;
var y = Math.sin(radians) * distance;

Here's a very basic fiddle with square planets and everything.

like image 89
shennan Avatar answered Dec 31 '22 14:12

shennan