通过鼠标在OpenGL中移动形状

3
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;

}

当应用程序运行时,我按下鼠标后它会画一个矩形,但矩形随后消失了。我错在哪里?

没有投影的情况下,OpenGL 中的屏幕坐标范围为 [-1, 1]。由于在您的情况下 x 和 y 是 int 类型,它们很可能包含像素坐标(范围为 [0,宽度或高度])。 - BDL
1个回答

2

不要在鼠标处理程序中直接渲染内容,而是更新对象位置并使用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;
}

非常感谢。您的意思是在鼠标处理程序中不要调用矩形,只需更新坐标并调用glutPostRedisplay()。 - user3059066
没错,那就是我想表达的意思。 - genpfault

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接