4
votes

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?

2

2 Answers

7
votes

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.

3
votes

I would do something like this:

distance = 100; //distance between earth and sun.

getXPosition = function(angle){
    return distance*(Math.cos(Math.PI * (angle/180))); 
};

getYPosition = function(angle){
    return distance*(Math.sin(Math.PI * (angle/180))); 
};

var x = getXPosition(45); //70.71 from the sun
var y = getYPosition(45); //70.71 from the sun

And to get the final position just do this:

x += 200; //200 = sun position
y -= 200; //200 = sun position