Search code examples
openglmatrixgraphicsglm-math

How to transform input coordinates in 2D Orthographic projection?


I generate the transformation matrix by the glm::ortho function.
I want the origin in the middle,[EDIT] x axis to the right, y to the up.[/EDIT]

That works fine when drawing stuff, but whenever I get a mouse input from the Window, (0,0) is at the top left.

What is the general way of handling this transformation?
I am now using a very ad-hoc and hacky way.

    y= sizey-y;
    x-=sizex/2;
    y-=sizey/2;

Solution

  • The general way to handle this would be:

    Translate (-sizex/2, sizey/2, 0.0); // Y translation:  -sizey/2 + sizey = sizey/2
    Scale     ( 1.0,        -1.0, 1.0);
    

    This produces the following matrix:

    |1.0  0.0 0.0 0.0|   |1.0 0.0 0.0 -sizex/2|     |1.0  0.0 0.0 -sizex/2|
    |0.0 -1.0 0.0 0.0| * |0.0 1.0 0.0  sizey/2|  =  |0.0 -1.0 0.0 -sizey/2|
    |0.0  0.0 1.0 0.0|   |0.0 0.0 1.0   0.0   |     |0.0  0.0 1.0    0.0  |
    |0.0  0.0 0.0 1.0|   |0.0 0.0 0.0   1.0   |     |0.0  0.0 0.0    1.0  |
    

    You can multiply your input coordinates by that matrix to transform them, but what you had originally in your question is much simpler.