开发者

how to get relative x and y position from mouse click

In my mouse callback, i need to find out where the mosuebutton was clicked relative to the origin(so I need the -1 to 1 value) In the mosue calledback, the GLint is return the value 400 or whatever the x position is. How can I get the relative x position or how 开发者_C百科can I convert the x value?

void mouseClicked(GLint button,GLint state,GLint x,GLint y)
{
    if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
    {
        //get x of square clicked
        if(x<0.0)
        {
            cout<<"left side of the screen"<<endl;
        }
    }
}


A mouse click lacks one important information: The depth of where you click. All you have is a 2D point on the screen. However this maps to a ray into the scene. The best you can do is determine that ray from the mouse click. For this you need to unproject from the viewport to some point on that ray.

For this you need to:

  1. reverse the viewport mapping, i.e. map the mouse click coordinates in the viewport back to the range [-1,1] in either coordinate (this gives you NDC), we silently assume the depth will be 1.

  2. un-project, i.e. multiply the NDC with depth 1 by multiplying with the inverse projection matrix

  3. un-modelview, i.e. multiply the unprojected point by multiplying with the inverse modelview matrix.

If either projection or modelview matrix are singular, i.e. are not invertible this will not work.

The GLU library offers this, including matrix inversion in the function gluUnproject.

The result is a point on the ray. The ray itself is given by the ray equation r(\tau) = r_0 * tau, where r_0 is that one point you got.


a quick answer to your question would be like so:

void mouseClicked(GLint button,GLint state,GLint x,GLint y)
{
    // Convert x & y
    GLfloat fX = ((x/g_cxScreen) - 0.5) * 2;
    GLfloat fY = ((y/g_cyScreen) - 0.5) * 2;

    if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
    {
        //get x of square clicked
        if(x<0.0)
        {
            cout<<"left side of the screen"<<endl;
        }
    }
}

This assumes g_cxScreen and g_cyScreen are the screen width and height respectively. This will normalise your mouse coords.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜