Graphics Reference
In-Depth Information
The newly calculated relativeTarget vector is then used with Mathf.Atan2 to find an
angle of rotation:
// Calculate the target angle
targetAngle = Mathf.Atan2 ( relativeTarget.x,
relativeTarget.z );
// Atan returns the angle in radians, convert to degrees
targetAngle *= Mathf.Rad2Deg;
To enforce limits on the amount of rotation to apply in one step, the function uses Mathf.
Clamp to keep the angle less than the value of the float variable followTargetMaxAngle:
// The wheels should have a maximum rotation angle
targetAngle = Mathf.Clamp ( targetAngle,
-followTargetMaxTurnAngle-targetAngle,
followTargetMaxTurnAngle );
The next step is to use Transform.Rotate to turn the bot. targetAngle is multiplied
by modelRotateSpeed and again multiplied by Time.deltaTime to make the rotation time
based. This value is used by the Rotate function to turn the rotateTransform transform
(which takes three float parameters for x , y , and z rotation amounts):
// turn towards the target at the rate of modelRotateSpeed
rotateTransform.Rotate( 0, targetAngle * modelRotateSpeed *
Time.deltaTime, 0 );
}
CanSee() does a simple line-of-sight check to see whether anything is between the bot
and its target. This is useful for cutting off chases when the target goes behind a wall or
somewhere unreachable by the AI bot.
It creates a normalized vector from the two positions and then uses this to cast a ray
from the bot out at the length from the maxChaseDistance variable:
public bool CanSee( Transform aTarget )
{
// first, let's get a vector to use for raycasting by
// subtracting the target position from our AI position
tempDirVec=Vector3.Normalize( aTarget.position -
myTransform.position );
// let's have a debug line to check the distance between the
// two manually, in case you run into trouble!
Debug.DrawLine( myTransform.position, aTarget.position );
// cast a ray from our AI, out toward the target passed in
// (use the tempDirVec magnitude as the distance to cast)
if( Physics.Raycast( myTransform.position +
( visionHeightOffset * myTransform.up ), tempDirVec, out
hit, maxChaseDistance ))
{
When a hit occurs in the raycast, all this code does is check to see whether the hit
object is the target. If it is the target, we now know that there is nothing blocking the way
so it can return true; otherwise, it falls through to return false at the end of the function:
Search WWH ::




Custom Search