The final method we will cover for picking involves casting rays in the scene to determine the nearest object to the viewer. We will use the same scene as in the last two recipes, three cubes (red, green, and blue colored) placed near the origin.
The code for this recipe is in the Chapter2/Picking_SceneIntersection
folder. Relevant source files are in the Chapter2/src
folder.
For picking with scene intersection queries, take the following steps:
Get two object-space points by unprojecting the screen-space point (
x, HEIGHT-y
), with different depth value, one at z=0 and the other at z=1:glm::vec3 start = glm::unProject(glm::vec3(x,HEIGHT-y,0), MV, P, glm::vec4(0,0,WIDTH,HEIGHT)); glm::vec3 end = glm::unProject(glm::vec3(x,HEIGHT-y,1), MV, P, glm::vec4(0,0,WIDTH,HEIGHT));
Get the current camera position as
eyeRay.origin
and geteyeRay.direction
by subtracting and normalizing the difference of the two object...