Search code examples
c++vectormath

Simulating planet orbit with vectors


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?


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.