0
votes

I'm trying to simulate the solar system and need to get the moon to orbit a planet orbiting the sun

i am currently using the following code to rotate the planets

glPushMatrix();
        glRotated((GLdouble)(spin*earth.speed), 0.0, 0.0, 1.0);
        glTranslated(earth.xPos, earth.yPos, earth.zPos);
        earth.draw();
glPopMatrix();

i'm trying to use the code below to make my moon orbit the earth however at the moment all i can do is rotate around a specific point.

glPushMatrix();
    //define one time only start location
    bool start = true;
    if (start)
    {
        glTranslated(earthMoon.xPos, earthMoon.yPos, earthMoon.zPos);
        start = false;
    }
    //orbit earths start point
    //perfectly fits around earth
        glTranslatef(-0.1, -0.1, 0);
        glRotatef(spin*10, 0, 0, 1);
        glTranslatef(0.1, 0.1, 0);
        // need translation vector to follow earth


    //glTranslated(earthMoon.xPos, earthMoon.yPos, earthMoon.zPos);
    earthMoon.draw();
glPopMatrix();

i think what i need to do is find some way of knowing earths position from the rotatef function.

I have a class for the planets with the following attributes and methods:

float radius;
float xPos;
float yPos;
float zPos;
float speed;
planet(float r, float x, float y, float z, float speed);
~planet();
void draw(void)
{
    glPushMatrix();
        glColor3f(0.0, 1.0, 1.0);
        glutSolidSphere(radius, 20, 10);
    glPopMatrix();
}

the class' coordinates do not get updated when the planet rotates

Does anyone know how to get this to work?

2

2 Answers

1
votes

Don't pop your matrix once you drew earth,
then your new referential will be the earth position, you just have to call the moon drawing code and it will rotate around your earth.

0
votes

Found a fix that works as intended in case anyone else is struggling with this concept

//earth
    glPushMatrix();
        //earth orbit
        glRotated((GLdouble)(spin*earth.speed), 0.0, 0.0, 1.0);
        glTranslated(earth.xPos, earth.yPos, earth.zPos);
            //earth mooon
        glPushMatrix();
            //orbit around earth
            glRotatef(spin * 5, 0, 0, 1);
            glTranslatef(0.1, 0.1, 0.0);
            //rotate around self
            glRotated((GLdouble)spin, 0.0, 1.0, 0.0);
            //draw moon
            earthMoon.draw();
        glPopMatrix();
        //rotate around self
        glRotated((GLdouble)spin, 0.0, 1.0, 0.0);
        //draw earth
        earth.draw();
    glPopMatrix();
    //

Hope this helps anyone else