Getting the mouse position when ortho is set from -1.0 to 1.0

Viewed 65

I'm new to OpenGL/GLUT using c. I want to implement a button that has a callback when a user clicks it. To understand that better, I have a simple program that draws a dot where the mouse is clicked. Here's the code

#include <freeglut.h>
GLint   mousePressed = 0;
GLfloat mouseX, mouseY;
GLint windowHieght = 400;
GLint windowWidth = 500; 

void myDisplay()
{
    glClear(GL_COLOR_BUFFER_BIT);

    if (mousePressed)
    {
        // draw the dot
        glBegin(GL_POINTS);

        // draw the vertex at that point
        glVertex2f(mouseX, mouseY);

        glEnd();
    }

    glFlush();
}
void myMouseButton(int button, int state, int x, int y)
{
    if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
        exit(0);

    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
    {
        mousePressed = 1;

        mouseX = (GLfloat)x / (GLfloat)windowWidth;

        mouseY = (GLfloat)windowHieght - (GLfloat)y;  
        mouseY = mouseY / (GLfloat)windowHieght;

        glutPostRedisplay();
    }
void main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB);
    glutInitWindowSize(windowWidth, windowHieght);
    glutInitWindowPosition(100, 150);
    glutCreateWindow("dots");
        gluOrtho2D(0.0, 1.0, 0.0, 1.0);
    glutDisplayFunc(myDisplay);
    glutMouseFunc(myMouseButton);

    initializeGL();

    glutMainLoop();
}

Everything works as expected, but when I change the ortho to (-1.0,1.0,-1.0,1.0), I don't get the same result. How can I get the same behavior?

1 Answers

Your myMouseButton function relies on the orthographic projection being 0-1 on both axes. Since you have changed that, you need to change the math in this function too.

To be very brief, your new orthographic co-ordinate range can be thought of as the old range scaled by 2 and then having 1 subtracted...

[0, 1] * 2 - [1, 1] => [-1, 1]

So you just need to do the same thing to your existing mouse co-ordinate equations.

mouseX = mouseX * 2.0f - 1.0f;
mouseY = mouseY * 2.0f - 1.0f;
Related