Question

To better understand how vectors work, I'm trying to create a very simple simulation of the earth orbiting the sun. Currently, all I want is for the earth to go around the sun in a circle. No laws of physics are taken into account.

I thought that what I was doing would work, however it creates some kind of a movement into a fibonacci spiral.

// initial positions
vec2 sun(0.0,0.0);
vec2 earth(10.0,0.0);

while(true) {

    vec2 earthToSun = normalize(sun - earth); // this is the vector 'pointing from the earth towards the sun'
    vec2 speedVector = vec2(-earthToSun.y, earthToSun.x); // this is the vector perpendicular to the earthToSun vector

    earth = earth + earthToSun + speedVector; // move the earth along the resulting vector

}

What is wrong in my calculations?

Was it helpful?

Solution

Why not just do it with trigonometry:

#define PI 3.1415926
float r = 10.0;
for (int theta=0; theta<2*PI; theta += 0.01)
{
    float x = r*cos(theta),
          y = r*sin(theta);
    earth = vec2(x, y);
}

Obviously, alter the period, starting value of theta, increment, etc. as you see fit.

OTHER TIPS

Your initial conditions should be

vec2 sun(0.0,0.0);
vec2 earth(10.0,0.0);
vec2 speedVector = vec2(-earthToSun.y, earthToSun.x);

That looks good. However, there are two problems with your equations.

  1. The position of your earth should change over time like this:

    vec2 earthToSun = normalize(sun - earth);
    earth = earth + earthToSun;  // no speedVector added here
    

    Note that I did not add speedVector to earth in the update code. What you did there is accelerate your earth throughout your simulation.

  2. Your normalize function will have to normalize by the squared distance. I am not sure how you implemented that. F = g m1 m2 / r ^ 2. I suspect that your normalize only devides by r, not r ^ 2. Check https://en.wikipedia.org/wiki/Gravitational_constant for reference

Your earth will not necessarily go in a circle. Most likely it will be an elliptical orbit. Also make sure to choose a small enough step size. Per iteration, earth should change only by a small fraction of its distance to the sun, or otherwise you will accumulate obvious integration errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top