在Opengl中通过鼠标移动形状

时间:2014-10-28 15:38:34

标签: animation opengl sprite mouse

void Rectangle(void) { 

glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_QUADS);
    glColor3f(1.0,0.0,0.0);
    glVertex2f(m_x-0.25,m_y-0.25);
    glColor3f(1.0,0.0,0.0);
    glVertex2f(m_x-0.25,m_y-0.75);
    glColor3f(1.0,0.0,0.0);
    glVertex2f(m_x-0.75,m_y-0.75);
    glColor3f(1.0,0.0,0.0);
    glVertex2f(m_x-0.75,m_y-0.25);
glEnd();
glutSwapBuffers();

我想将矩形移动到按下鼠标的位置。 m_x和m_y是全局变量。这个函数调用了主要的glutDisplayFunc(Rectangle),鼠标函数如下:

void mouse(int button,int state,int x,int y)  
  switch(button)
{
case GLUT_LEFT_BUTTON:
    if(state==GLUT_DOWN)
    {
        m_x=x;
        m_y=y;
        Rectangle();
        glutSwapBuffers();
    }
    break;

default:
    break;

}

当应用程序运行时,按下鼠标后矩形会丢失一个矩形。我错了什么?

1 个答案:

答案 0 :(得分:0)

不要像这样在鼠标处理程序中渲染内容,只需更新对象位置并使用glutPostRedisplay()对重绘进行排队:

#include <GL/glut.h>

float objX = 100;
float objY = 100;
float objSize = 50;
bool dragging = false;
void mouse( int button, int state, int x, int y )
{
    if( GLUT_DOWN == state )
    {
        bool colliding = 
            objX - objSize <= x && x <= objX + objSize
            &&
            objY - objSize <= y && y <= objY + objSize;
        if( colliding )
        {
            dragging = true;
            objX = x;
            objY = y;
            glutPostRedisplay();
        }
    }
    else
    {
        dragging = false;
    }
}

void motion( int x, int y )
{
    if( dragging )
    {
        objX = x;
        objY = y;
        glutPostRedisplay();
    }
}

void drawRect( float x, float y, float size )
{
    glPushMatrix();
    glTranslatef( x, y, 0.0f );
    glScalef( size, size, 1.0f );
    glBegin( GL_QUADS );
    glColor3ub( 255, 255, 255 );
    glVertex2f( -1, -1 );
    glVertex2f(  1, -1 );
    glVertex2f(  1,  1 );
    glVertex2f( -1,  1 );
    glEnd();
    glPopMatrix();
}

void display()
{
    glClearColor( 0, 0, 0, 1 );
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    const double w = glutGet( GLUT_WINDOW_WIDTH );
    const double h = glutGet( GLUT_WINDOW_HEIGHT );
    glOrtho( 0, w, h, 0, -1, 1 );

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    drawRect( objX, objY, objSize );

    glutSwapBuffers();
}

int main(int argc, char **argv)
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
    glutInitWindowSize( 600, 600 );
    glutCreateWindow( "GLUT" );
    glutDisplayFunc( display );
    glutMouseFunc( mouse );
    glutMotionFunc( motion );
    glutMainLoop();
    return 0;
}