Introduction
This tutorial is really short. I am not going to describe generally how to get a picking ray, but a good reference can be found here. I will show how the FreeCamera class can easily implement a GetPickRay method
The GetPickRay Method
This method takes in normalized x and y coordinates of a mouse click on the screen. Normalized means that the center of the screen is (0, 0), the upper right corner is (1, 1) and the lower left is (-1,-1). The return value is a Ray, which has two vector components, an initial position and a normalized vector direction. Basically, this method finds the position on the near plane the mouse clicked and makes a vector from there straight into the screen (if it were drawn, it would look like a point).
Here is the implementation:
public Ray GetPickRay(float x, float y) { Vector3 vector = ( ( N * -1 ) * m_near) + (U * m_right * x) + (V * m_top * y); Vector3 pos = vector + Position; vector.Normalize(); return new Ray(pos, vector); }
Conclusion
The pick ray is extremely useful for "selecting" elements in an OpenGL scene with the mouse. The only thing to do is test whether the picking ray collides (extended) or intersects with an element. Abstracting an OpenGL camera into the FreeCamera class has
made it extremely intuitive for me to render and interact with the scene. Writing these tutorials has given me a much better understanding of OpenGL and how it works. If there are misleading statements in any of these tutorials, please, kindly leave a comment. I would like to fix any errors and learn from those mistakes!