Game Development Reference
In-Depth Information
But a 2D point can't be multiplied by a 4×4 matrix, so before the point can be
multiplied by this matrix, it must be converted to homogenous coordinates. This
requires z- and w-components to be added to the 2D point. The z-component is
usually set to either 0 or 1, depending on whether the 2D point should be conver-
ted to a point on the near plane or the far plane, respectively. And since it's a point,
the w-component should always be 1. The following
Unproject
function takes
a 4D vector, because it assumes that it already has its z- and w-components set ap-
propriately:
function
Unproject(
Vector4
screenPoint
,
Matrix
cam-
era
,
Matrix
projection
)
// Compute inverse of camera * projection
Matrix
unprojection
=
camera
*
projection
unprojection
.Invert()
return
Transform(
screenPoint
,
unprojection
)
end
The
Unproject
function can then be used to calculate two points: the mouse po-
sition unprojected onto the near plane (
z
= 0) and the mouse position unprojected
onto the far plane (
z
= 1). These two points in world space can then be used as the
start and end points of a ray cast that tests against all of the selectable objects in
the world. Because there can potentially be multiple objects the ray cast intersects
with, the game should select the closest one.
Figure 8.13
shows the basic premise
behind picking.