【问题标题】:How do I make a simple 2D shape move using the keyboard with GLUT如何使用带有 GLUT 的键盘进行简单的 2D 形状移动
【发布时间】:2013-12-09 23:50:38
【问题描述】:

我正在尝试在 GLUT 中制作一个简单的方形,使其具有键盘功能,使其根据您按下的键在屏幕上移动。

一直在尝试,但无论我尝试什么都行不通。

方块代码

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

【问题讨论】:

标签: opengl glut


【解决方案1】:

您需要一些键盘回调和位置更新逻辑。

试试这样的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-28
    • 2018-12-13
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    相关资源
    最近更新 更多