Game Development Reference
In-Depth Information
13.5 “Walking” on the Terrain
After we have constructed a terrain, we would like the ability to move
the camera so that it simulates us walking on the terrain. That is, we
need to adjust the camera's height (y-coordinate) depending on the part
of the terrain that we are standing on. In order to do this we first need
to find the cell we are in given the x- and z-coordinates of the camera's
position. The Terrain::getHeight function does this; it takes the
camera's x- and z-coordinates as parameters and returns the height the
camera needs to be set to in order for it to be on the terrain. Let's now
walk through its implementation.
float Terrain::getHeight(float x, float z)
{
// Translate on xz-plane by the transformation that takes
// the terrain START point to the origin.
x = ((float)_width / 2.0f) + x;
z = ((float)_depth / 2.0f) - z;
// Scale down by the transformation that makes the
// cellspacing equal to one. This is given by
// 1 / cellspacing since cellspacing*1/cellspacing = 1.
x /= (float)_cellSpacing;
z /= (float)_cellSpacing;
We first translate by the transformation that takes the start point of the
terrain to the origin. Next, we scale by the inverse of the cell spacing
variable; this scaling sets the cell spacing to 1. Then we switch to a
new frame of reference where the positive z-axis points “down.” Of
course, there is no code that changes the frame of reference, but it is
now understood that + z goes down. Figure 13.9 shows these steps
graphically.
Figure 13.9: The ter-
rain grid before and
after translating start
to the origin, making
the cell spacing equal
to 1 and flipping the
z-axis
We see that our changed coordinate system matches the ordering of a
matrix. That is, the upper-left corner is at the origin, the column count
increases in the right direction, and the row count increases in the
Search WWH ::




Custom Search