Hi,
(I replied to your post earlier, but realized
there was a much easier way, so I deleted it and wrote this one).
To convert from window coordinates (I'll
use the mouse here) to world coordinates, you can simply use
the
glm::unProject() function:
ivec2 mouse =
...; // obtain mouse coordinates in the mouseMove() function.
mat4 projection =
cam.getProjectionMatrix() * cam.getViewMatrix();
int w = getWindowWidth();
int h = getWindowHeight();
vec4 viewport =
vec4( 0, h, w, -h ); // vertical flip is required
vec3 worldCoordinate =
glm::unProject( vec3( mouse, 0 ), mat4(), projection,
viewport );
When drawing your content, you should store the
model matrix. This way, you can later also retrieve local coordinates:
mat4 model = glm::rotate(
glm::radians( 30.0f ), vec3( 0, 0, 1 ) );
gl::pushModelMatrix();
gl::setModelMatrix(
model );
gl::drawStrokedRect(
Rectf( 0, 0, 100, 100 ) );
gl::popModelMatrix();
vec3 localCoordinate =
glm::unProject( vec3( mouse, 0 ), model, projection, viewport );
if( Rectf( 0, 0, 100,
100 ).contains( vec2( localCoordinate ) ) )
CI_LOG_I(
"Rectangle touched!" );
-Paul
P.S.: more on the theory, and how to apply it for
perspective projections, can be found
here.
P.P.S.: if you're going to use glm::unProject a lot, it
will be faster to call it once per frame to obtain a worldCoordinate (use mat4() for the second
parameter), then for each object on screen multiply it by its
inverse model matrix to obtain the local coordinate: vec4 localCoordinate =
glm::inverse( model ) * vec4( worldCoordinate, 1 ).