Graphics Reference
In-Depth Information
If you need to debug waypoint-following code, uncommenting the code below will
give a visual representation of where the vehicle should be aiming. When uncommented,
it will position a gameObject named debugBox at the position of the current waypoint:
// position our debug box at the current waypoint so we can
// see it (uncomment if you're debugging!)
// debugBox.transform.position=currentWaypointTransform.
position;
}
To make sure that the player is always heading in the right direction around the track,
the CheckWrongWay() function uses the waypoints system to look ahead to the next way-
point and check the angle of the vehicle versus the ideal angle to reach the waypoint.
When the angle goes over a certain threshold (here, it is set to 90°), then the wrong-way
message is displayed.
First up, the function checks that currentWaypointTransform has something in it. If
this reference was at null, it would break the code. Rather than that, the check will return
out of the function instead:
public void CheckWrongWay()
{
if(currentWaypointTransform==null)
return;
The script will use the waypoint from currentWaypointTransform to check that the
vehicle is traveling in the right direction. The first step in doing that is to calculate a vector,
relative to the vehicle, with Transform.InverseTransformPoint(). Essentially, what hap-
pens here is that the world vector provided by currentWaypointTransform.position is con-
verted to the local space belonging to myTransform (the vehicle), providing relativeTarget
with its vector:
Vector3 relativeTarget =
myTransform.InverseTransformPoint (currentWaypointTransform.
position);
Though a technical description of Mathf.Atan2 would be complicated, its use here
can be summarized relatively easily; in this code, Atan2 is used to convert the x and z
values of the vector relativeTarget into an angle:
targetAngle = Mathf.Atan2 (relativeTarget.x,
relativeTarget.z);
The result of Mathf.Atan2 will be in radians, so a quick call to Mathf.Rad2Deg is
required to convert it over to degrees:
targetAngle *= Mathf.Rad2Deg;
Since relativeTarget was a vector relative to the vehicle, we can assume that the value
of targetAngle of 0° will be forwarded along the vehicle's forward axis and that 90° or
−90° will be out to its right or left. In effect, targetAngle now holds the result of how many
degrees the vehicle (along its forward vector) is out from facing the waypoint. The next
Search WWH ::




Custom Search