2013-12-09 83 views
-2

我試圖使GLUT中的一個簡單的方形形狀具有鍵盤功能,這將使其按照您按哪個鍵在屏幕上移動。如何使用GLUT的鍵盤做一個簡單的2D形狀移動

一直試圖做到這一點,但無論我嘗試將無法正常工作。

代碼爲方形

glPushMatrix(); 
    glTranslatef(-0.9, 0.90, 0); 
    glBegin(GL_POLYGON); 
     glColor3f(0.90, 0.91, 0.98); 
     glVertex2f(-0.10,-0.2); 

     glColor3f(0.329412, 0.329412, 0.329412); 
     glVertex2f(-0.10, 0.2);       

     glColor3f(0.90, 0.91, 0.98); 
     glVertex2f(0.10, 0.2); 


     glVertex2f(0.10,-0.2); 
    glEnd(); 
    glPopMatrix(); 
+0

它不工作,因爲你沒有自己看鑰匙的任何代碼。 – usr2564301

+0

我知道,我已經刪除了我所做的嘗試。知道我可以遵循的任何教程等? – Siyico

+0

第一個隨機谷歌Hit:http://www.lighthouse3d.com/tutorials/glut-tutorial/keyboard/ – usr2564301

回答

0

你需要一些鍵盤迴調和位置更新邏輯。

給這樣的一個嘗試:

#include <GL/glut.h> 
#include <map> 

std::map< int, bool > keys; 
void special(int key, int x, int y) 
{ 
    keys[ key ] = true; 
} 
void specialUp(int key, int x, int y) 
{ 
    keys[ key ] = false; 
} 

void display() 
{ 
    static float xpos = 0; 
    static float ypos = 0; 

    const float speed = 0.02; 
    if(keys[ GLUT_KEY_LEFT ]) 
    { 
     xpos -= speed; 
    } 
    if(keys[ GLUT_KEY_RIGHT ]) 
    { 
     xpos += speed; 
    } 
    if(keys[ GLUT_KEY_UP ]) 
    { 
     ypos += speed; 
    } 
    if(keys[ GLUT_KEY_DOWN ]) 
    { 
     ypos -= speed; 
    } 

    glClearColor(0, 0, 0, 1); 
    glClear(GL_COLOR_BUFFER_BIT); 

    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    glOrtho(-2, 2, -2, 2, -1, 1); 

    glMatrixMode(GL_MODELVIEW); 
    glLoadIdentity(); 

    glTranslatef(xpos, ypos, 0); 
    glTranslatef(-0.9, 0.90, 0); 
    glBegin(GL_POLYGON); 
    glColor3f(0.90, 0.91, 0.98); 
    glVertex2f(-0.10,-0.2); 

    glColor3f(0.329412, 0.329412, 0.329412); 
    glVertex2f(-0.10, 0.2);       

    glColor3f(0.90, 0.91, 0.98); 
    glVertex2f(0.10, 0.2); 

    glVertex2f(0.10,-0.2); 
    glEnd(); 

    glutSwapBuffers(); 
} 

void timer(int value) 
{ 
    glutTimerFunc(16, timer, 0); 
    glutPostRedisplay(); 
} 

int main(int argc, char **argv) 
{ 
    glutInit(&argc, argv); 
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); 
    glutInitWindowSize(640, 640); 
    glutCreateWindow("GLUT"); 
    glutDisplayFunc(display); 
    glutSpecialFunc(special); 
    glutSpecialUpFunc(specialUp); 
    glutTimerFunc(0, timer, 0); 
    glutMainLoop(); 
    return 0; 
}