2014-12-23 73 views
3

我需要圍繞太陽圍繞地球旋轉OpenGL。我目前能夠圍繞太陽旋轉它,但是我需要將它旋轉到橢圓軌道。現在橢圓已經生成,但我無法弄清楚如何沿着橢圓旋轉它。在橢圓路徑中旋轉地球:OpenGL

繪製功能看起來像:

//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

您需要參數才能在每個時間步獲得地球的目標位置 –

+0

借調,您不能簡單地使用旋轉+平移來獲得橢圓上的正確位置。試着看看這個:http://en.wikipedia.org/wiki/Ellipse#General_parametric_form – vesan

回答

1
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. 

所以,你可以在橢圓上的每個點繪製球體。

定義兩個變量跟蹤(X,Y)座標爲沿橢圓

float xForEarth, yForEarth; 

和計數器計數的程度(從0到360,然後再次轉換地球0)

int counterForEarth = 0; 

,並使用下面的代碼(您的繪圖方法內),使橢圓並繪製地球上:

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's 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();