Converting Window coordinates to Axis coordinates in OpenGL
Im creating a开发者_如何学编程 simple program in OpenGL to draw rectangles with the mouse. My goal is to click somewhere, drag the mouse and create a rectangle just like you do in paint or any other design program.
I have a view defined like:
glMatrixMode(GL_PROJECTION);
glOrtho(AXIS_X_MIN, AXIS_X_MAX, AXIS_Y_MIN, AXIS_Y_MAX, AXIS_Z_MIN, AXIS_Z_MAX);
and a window defined this way:
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
How can I convert the window coordinates which go from 0 to WINDOW_WIDTH and from 0 to WINDOW_HEIGHT into axis coordinates and respective quadrants?
Try:
double x = x_mouse / (double) WINDOW_WIDTH
* (AXIS_X_MAX - AXIS_X_MIN) + AXIS_X_MIN;
double y = (1 - y_mouse / (double) WINDOW_HEIGHT)
* (AXIS_Y_MAX - AXIS_Y_MIN) + AXIS_Y_MIN;
If you don't want to make the calculations by "hand", you can always check this small article, that makes use of a function from GLU library that shall do this internally.
http://steinsoft.net/index.php?site=Programming/Code%20Snippets/OpenGL/no8
gluUnProject — transforms map window coordinates to object coordinates. To be honest, I barely have any idea of how it works. You can check it out here: OpenGL - gluUnProject
Also if you try this it should work:
float coorX = mouseX * width / WINDOW_WIDTH + AXIS_X_MIN;
float coorY = mouseY * heigth/ WINDOW_HEIGHT + AXIS_Y_MIN;
精彩评论