Rotate the Earth in an Elliptical Path: OpenGL

I need to rotate the Earth around the Sun in OpenGL . Currently, I can rotate it around the sun, but I need to rotate it in an elliptical orbit . The ellipse has now been released, but I cannot figure out how to rotate it along that ellipse.

The Draw function looks like this:

    //orbit
    glColor3f(1,1,1); 
    drawEllipse(3.2f,1.0f); //draws ellipse 
    //sun
    glTranslatef(0,0,0);//suns position
    glColor3d(1,1,0);
    glutSolidSphere(2,50,50);

    //EARTH
    glRotatef(angle,0.0f,1.0f,0.0f);
    glTranslatef(6.0f,0.0f,0.0f);//postion earths


    glPushMatrix();
    glRotatef(angle2, 0.0f,1.0f,0.0f);
    glColor3d(0.5,0.8,1);

    glutSolidSphere(1,50,50);
    glPopMatrix();

      

+3


source to share


1 answer


OpenGL does not store what you draw. If you draw a line in OpenGL, then OpenGL 
will take that line, perform various math operations on it, and write pixels
 into a framebuffer that makes the shape of a line. OpenGL does not remember
 that you drew a line; all OpenGL can do is write pixels to the framebuffer.

      

So, you can draw a sphere at each point of the ellipse.

Define two variables that track the (x, y) coordinates to translate the Earth into an ellipse

float xForEarth, yForEarth;

      



And a counter that counts the degree (from 0 to 360 and then back to 0)

int counterForEarth = 0;

      

And use the following code (inside your paint method) to make an Ellipse and draw the Earth on it:

glBegin(GL_POINTS);
    for (int i=0; i < 360; i++) 
    { 
        float degInRad = i*DEG2RAD; //const float DEG2RAD = 3.14159/180.0;
        glVertex3f(cos(degInRad)*6.0, 
            sin(degInRad)*2.3,0.0f);
    }
    glEnd();
    if(counterForEarth>359)
        counterForEarth = 0;//reset to 0 when becomes 360
    else
        counterForEarth++;//this will control the speed. Do counterForEarth += 2 to increase it speed and vice-versa

    xForEarth = cos(counterForEarth*DEG2RAD)*6.0f;//to change the x co-ordinate
    yForEarth = sin(counterForEarth*DEG2RAD)*2.3f;//to change the y co-ordinate
    glPushMatrix();
    glTranslatef(xForEarth,yForEarth,0.0f);
    glRotatef(angle,0.0f,1.0f,0.0f);
    glutSolidSphere(.4,30,30);//draw Earth
    glPopMatrix();

      

+1


source







All Articles