Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

opengl - How do I make a simple 2D shape move using the keyboard with GLUT

I'm trying to make a simple square shape in GLUT have keyboard functions which will make it move around the screen according to which keys you press.

Been attempting to do it but whatever I attempt won't work.

Code for the square

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need some keyboard callbacks and position update logic.

Give something like this a try:

#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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...