2012-05-18 120 views
-4

我想用OpenGl功能在C++中繪製一個堅實的立方體,但是我想將它繪製在期望的位置,例如glVertex3f(20,5,-35)。我如何在給定的位置繪製一個立方體?C++中的OpenGl實體立方體

+1

1.你有什麼試過的? (告訴我們代碼!) 2.您在哪裏遇到問題? – tzaman

+1

添加到什麼tzaman說:http://mattgemmell.com/2008/12/08/what-have-you-tried/ – Samveen

回答

2

glTranslatef(x,y,z)。谷歌它,我認爲也有2D版本。但是這會將參考幀轉換爲堆棧。如果需要設置更復雜的轉換,則需要調用glpopmatrix和glpushmatrix。小心拼寫和使用這些。

2

要匹配你的問題,並在OpenGL(兼容性配置文件),你可以使用此代碼來繪製一個立方體:

void drawCube(float x, float y, float z) 
    { 
    glBegin(GL_QUADS); 
    glVertex3f(-1.0f+x, -1.0f+y, -1.0f+z); 
    glVertex3f(1.0f+x, -1.0f+y, -1.0f+z); 
    glVertex3f(1.0f+x, 1.0f+y, -1.0f+z); 
    glVertex3f(-1.0f+x, 1.0f+y, -1.0f+z); 

    glVertex3f(-1.0f+x, -1.0f+y, -1.0f+z); 
    glVertex3f(-1.0f+x, -1.0f+y, 1.0f+z); 
    glVertex3f(-1.0f+x, 1.0f+y, -1.0f+z); 
    glVertex3f(-1.0f+x, 1.0f+y, 1.0f+z); 

    glVertex3f(-1.0f+x, -1.0f+y, -1.0f+z); 
    glVertex3f(-1.0f+x, -1.0f+y, 1.0f+z); 
    glVertex3f(1.0f+x, -1.0f+y, 1.0f+z); 
    glVertex3f(1.0f+x, -1.0f+y, -1.0f+z); 

    glVertex3f(-1.0f+x, -1.0f+y, 1.0f+z); 
    glVertex3f(1.0f+x, -1.0f+y, 1.0f+z); 
    glVertex3f(1.0f+x, 1.0f+y, 1.0f+z); 
    glVertex3f(-1.0f+x, 1.0f+y, 1.0f+z); 

    glVertex3f(-1.0f+x, -1.0f+y, 1.0f+z); 
    glVertex3f(1.0f+x, -1.0f+y, 1.0f+z); 
    glVertex3f(1.0f+x, 1.0f+y, 1.0f+z); 
    glVertex3f(-1.0f+x, 1.0f+y, 1.0f+z); 

    glVertex3f(-1.0f+x, 1.0f+y, -1.0f+z); 
    glVertex3f(-1.0f+x, 1.0f+y, 1.0f+z); 
    glVertex3f(1.0f+x, 1.0f+y, 1.0f+z); 
    glVertex3f(1.0f+x, 1.0f+y, -1.0f+z); 

    glEnd(); 
    } 

我不推薦這個功能,使用替代glTranslatef(x, y, z)解決discribed在另一個答案。喜歡這個功能:

void drawCube(float x, float y, float z) 
    { 
     glPushMatrix(); 
     glTranslatef(x, y, z); 

     glBegin(GL_QUADS); 
     glVertex3f(-1.0f,-1.0f ,-1.0f); 
     glVertex3f(1.0f, -1.0f, -1.0f); 
     glVertex3f(1.0f, 1.0f, -1.0f); 
     glVertex3f(-1.0f, 1.0f, -1.0f); 

     glVertex3f(-1.0f, -1.0f, -1.0f); 
     glVertex3f(-1.0f, -1.0f, 1.0f); 
     glVertex3f(-1.0f, 1.0f, -1.0f); 
     glVertex3f(-1.0f, 1.0f, 1.0f); 

     glVertex3f(-1.0f, -1.0f, -1.0f); 
     glVertex3f(-1.0f, -1.0f, 1.0f); 
     glVertex3f(1.0f, -1.0f, 1.0f); 
     glVertex3f(1.0f, -1.0f, -1.0f); 

     glVertex3f(-1.0f, -1.0f, 1.0f); 
     glVertex3f(1.0f, -1.0f, 1.0f); 
     glVertex3f(1.0f, 1.0f, 1.0f); 
     glVertex3f(-1.0f, 1.0f, 1.0f); 

     glVertex3f(-1.0f,-1.0f ,1.0f); 
     glVertex3f(1.0f, -1.0f, 1.0f); 
     glVertex3f(1.0f, 1.0f, 1.0f); 
     glVertex3f(-1.0f, 1.0f, 1.0f); 

     glVertex3f(-1.0f, 1.0f, -1.0f); 
     glVertex3f(-1.0f, 1.0f, 1.0f); 
     glVertex3f(1.0f, 1.0f, 1.0f); 
     glVertex3f(1.0f, 1.0f, -1.0f); 
     glEnd(); 

     glPopMatrix(); 
    } 

這個功能還不夠完美,但它應該足夠了。快樂的編碼!

+1

我建議儘可能使用過剩。它們具有可以輕鬆製作實心立方體或線立方體的功能。 glutSolidCobe(glDouble size); – pippin1289