Search code examples
openglmouseeventglut

GLUT mouse Tracking and Drawing


I am making a simple GLUT program which tracks the mouse and put points on the path.

Well This is my code:

void init()
{
    glClearColor( 0.0, 0.0, 1.0, 1.0);
    glMatrixMode( GL_PROJECTION);
    gluOrtho2D( 0.0, 400.0, 0.0, 400.0);
    for(int i=0;i<5000;i++)
    {
        arr[i][0]=0;
        arr[i][1]=0;
    }
    glPointSize(10.0);
}

void drawPoints()
{
    glBegin( GL_POINTS );
    glColor3f( 0.0,0.0,0.0 );
    for ( int i = 0; i < z; i++ )
    {
        glVertex2f( arr[i][0], arr[i][1]);
    }
    glEnd();
}

void myDisplay()
{
    glClear( GL_COLOR_BUFFER_BIT);
    drawPoints();
    glutSwapBuffers();
    glutPostRedisplay();
}


void myMouseMove( int x, int y)
{
        arr[z][0]=x;
        arr[z++][1]=y;
}



int main( int argc, char ** argv)
{
    glutInit( &argc, argv);
    glutInitDisplayMode( GLUT_DOUBLE| GLUT_RGB);
    glutInitWindowPosition( 100, 100);
    glutInitWindowSize(600,600);
    glutCreateWindow( "Testing");
    init();
    glutDisplayFunc( myDisplay);
    glutPassiveMotionFunc( myMouseMove);
    glutMainLoop();
    return 0;
}

However I am having few problems:

  1. Y coordinate runs in opposite direction.
  2. Draws point ahead of cursor position(while moving in a direction).
  3. Is there any better way to do this?

Solution

  • The Y coordinate being flipped is actually expected behavior. Simply correct for it in your code and you should be fine.

    If you want to make sure that your rendered image and mouse cursor are completely synchronized, simply have glut hide the mouse cursor, and then render it yourself using OpenGL.