Search code examples
androidopengl-esprojectionprojection-matrix

How to get coordinates of touch screen points in ogl?


I am drawing map using OpenGL. I am getting map drawn after reading XML files and setting corresponding buffer. This map contains streets, highways and boundary. What i want is whenever i touch the map, the color of the specific layer should be changed.

The issue i am facing is this whenever i touch on the screen i am just getting the the screen pixel of the point where i touched. I want to convert this point into OpenGL coordinates so that i can match this point with the Map drawn and can highlight the selected point.

How to convert this point into OpenGL coordinates?


Solution

  • You need to unproject screen point into an OpenGL world space:

    vec3 UnProjectPoint( const vec3& Point, const max4& Projection, const mat4& ModelView )
    {
        vec4 R( Point, 1.0f );
    
        R.x = 2.0f * R.x - 1.0f;
        R.y = 2.0f * R.y - 1.0f;
        R.y = -R.y;
    
        R.z = 1.0f;
    
        R = Projection.GetInversed() * R;
        R = ModelView.GetInversed() * R;
    
        return R.ToVec3();
    }