Game Development Reference
In-Depth Information
There's more...
That's nice and all, but if we have terrain in our scene, which is not flat, the camera might
very well end up below the ground level. How can we remedy this? An easy way is to use
ray casting to check for the height of the terrain where the camera is looking. This can be
implemented as follows:
1. First, we need to make sure the terrain has CollisionShape :
terrain.addControl(new RigidBodyControl(0));
2. By supplying 0 to RigidBodyControl , we say that it doesn't have any mass
(and it won't be affected by gravity, if there were any). Since we're not supplying
CollisionShape , MeshCollisionShape will be created. Since the terrain
is of an irregular shape, a primitive (such as a box) isn't usable.
3. Next, we need to create a field for the terrain in AppState and a setter as well.
4. To actually find out the height of the terrain, we create a method called check-
Height , which returns the height as float.
5. Inside checkHeight , we shoot Ray , which originates from the camera's loca-
tion in the direction the camera is facing. An alternative could be to shoot it down
to get the height directly below the camera, as follows:
Ray ray = new Ray(cam.getLocation(),
cam.getDirection());
CollisionResults results = new
CollisionResults();terrain.collideWith(ray, results);
6. If we get a result from our ray, we get the y value from the collision point and re-
turn it as follows:
height =
results.getClosestCollision().getContactPoint().y;
7. Now, in the update method, just above the line where we set the location, we call
the checkHeight method. Be sure to apply the camDistance variable in or-
der to get the correct offset! This is implemented as follows:
camLocation.setY(checkHeight() + camDistance);
cam.setLocation(camLocation);
Search WWH ::




Custom Search