In the game and editor, pick is often used to pick up geometric objects in the world coordinate system. This weekend, we are free to sort out the formulas.
Step 1: Obtain picking Ray
The window coordinates W (x, y), width, height, and camera are given, and the origin and direction of the rays are returned.
Derivation process: Window coordinates-> screen (View) coordinates-> visual plane coordinates-> Ray origin and direction in the world coordinate system
1. The conversion formula from the window coordinate system to the screen coordinate system:
SX = wx/width
Sy = 1-Wy/height
2. Because the view is not necessarily the entire window area, the view coordinates are as follows:
Px = (SX-Port. Left)/(port. Right-Port. Left)
Py = (sy-Port. Bottom)/(port. Top-Port. Bottom)
3. The conversion formula from the perspective coordinate system to the visual plane coordinate system:
FX = frustum. Left + px * (frustum. Right-frustum. Left)
FY = frustum. Bottom + py * (frustum. Top-frustum. Bottom)
Frustum can be obtained based on the horizontal and vertical FOV field of view and the visual plane D.
Frustum. Left <= FX <= frustum. Right; frustum. Bottom <= FY <= frustum. Top.
4. According to the visual plane coordinates and the Dir, Up, And right axes of the camera in the world coordinate system, obtain the picking Ray:
Pickray. Origin = camera_worldlocation
Pickray. dir = camera_right * FX + camera_up * FY + camera_dir * 1
Step 2: Perform the intersection test based on the objects in the pick Ray and the world coordinate system, which can be a box test or a triangle test.
The first step is to obtain the ray origin and direction in the world space coordinate system, which is prone to errors. The second step is easy to understand and not described in detail.