Game Development Reference
In-Depth Information
Updating the player motion algorithm
To make our game character move through the level more smoothly, we will modify
the motion algorithm. Instead of relying on gravity on the rigid body to keep the player
anchored to the ground, we will cast a ray downward and glue the player to the poly-
gon directly below. In this way, the curvature of the terrain will play less of a role in
restricting the player. This can be achieved by performing the following steps:
1. Switch to the
MAIN
scene, and double click on the
PlayerControls
script
on the player. In the
UpdateMovement()
method, directly after the
Char-
acterController.Move()
method is called, declare a
RayCastHit
class
named
hitInfo
as shown in the following code. This class will be used to
return the position of the polygon from a raycast that is directly below the play-
er. By invoking a raycast downward, we can check what other GameObject is
intersected and use this information to glue the player to the ground directly at
the point of contact:
RayCastHit hitInfo;
2. We create a new ray that points straight down from the player. We use the
player's transform to determine the downward direction rather than the world
transform so that even if the player is rotated, the raycast will always look
down relative to the character as shown in the following code:
Ray r = new Ray(this.transform.position,
-Vector3.up);
3. We query the physics system by casting the previous ray and allowing the
PhysX integration to return the polygon that this raycast has hit, through the
hitinfo
variable, as shown in the following code:
Physics.Raycast( r, out hitinfo);
4. Finally, we set the
y
position of the character to the
y
position of the poly that
was hit in the raycast, plus an offset. We do this by creating a
new Vect-
or3
variable to assign to the
transform.position
variable as we cannot
assign to just a single component of this value type. The offset that we use to