I have a 3D scene with an infinite horizontal plane (parallel to the xz coordinates) at a height H along the Y vertical axis.
I would like to know how to determine the intersection between the axis of my camera and this plane.
The camera is defined by a view-matrix and a projection-matrix.
For a general line-plane intersection there are lot of answers and tutorials.
Your case is simple due to the plane is horizontal.
I suppose the camera is at
C(cx, cy, cz)
and it looks atT(tx, ty,tz)
.Then the line camera-target can be defined by:
For a horizontal plane, only a equation is needed:
y = H
. Substitute this value in the line equations and you getSo
Of course if your camera looks in an also horizontal line then
ty=cy
and there is not solution.There are two sub-problems here: 1) Extracting the position and view-direction from the camera matrix. 2) Calculating the intersection between the view-ray and the plane.
Extracting position and view-direction
The view matrix describes how points are transformed from world-space to view space. The view-space in OpenGL is usually defined such that the camera is in the origin and looks into the -z direction.
To get the position of the camera, we have to transform the origin [0,0,0] of the view-space back into world-space. Mathematically speaking, we have to calculate:
but when looking at the equation we'll see that we are only interrested in the 4th column of the inverse matrix which will contain 1
The orientation of the camera can be found by a similar calculation. We know that the camera looks in -z direction in view-space thus the world space direction is given by
Again, when looking at the equation, we'll see that this only takes the third row of the inverse matrix into account which is given by2
Calculating the intersection
We now know the camera position P and the view direction D, thus we have to find the x,z value along the ray
R(x,y,z) = P + l * D
where y equals H. Since there is only one unknown, l, we can calculate that fromThe intersection point is then given by pasting l back into the ray equation.
Notes
1 The indices assume that the matrix is stored in a column-major linear array.
2 Note, that the inverse of a matrix of the form
, where R is a orthogonal 3x3 matrix, is given by