Graphics Reference
In-Depth Information
public virtual int IsObstacleAhead()
{
obstacleHitType=0;
// quick check to make sure that myTransform has been set
if( myTransform==null )
{
return 0;
}
Along the way, doubts may set in as to whether or not things are working as they
should with the AI—to make it easier to visualize what is happening, the function includes
some Debug.DrawRay calls that will make lines appear in the editor where the rays are
being cast. This will only happen in the editor when Gizmos are set to true (use the Gizmos
icon above the window to set this):
// draw this raycast so we can see what it is doing
Debug.DrawRay(myTransform.position, ((myTransform.forward +
(myTransform.right * 0.5f)) * wallAvoidDistance));
Debug.DrawRay(myTransform.position, ((myTransform.forward +
(myTransform.right * -0.5f)) * wallAvoidDistance));
The actual raycasting happens next, using the AI bot's forward vector—myTransform.
forward—with an offset to the side—myTransform.right multiplied by half so that the
angle goes diagonally out from the bot—with the ray starting at myTransform.position.
The Physics.Raycast function as used here is given as follows:
bool Physics.Raycast( Vector3 origin, Vector3 direction, RayCastHit
hitInfo, distance)
The variable wallAvoidDistance is used as the distance parameter for raycasting, which
may be set in the Unity editor Inspector window. When the AI moves faster, it will usually
help the patrolling if this value is higher as the bot can look ahead further for obstacles.
If a call to Physics.Raycast finds something, it will return true, meaning we can easily
use it in an if statement:
// cast a ray out forward from our AI and put the 'result'
// into the variable named hit
if(Physics.Raycast( myTransform.position, myTransform.
forward + ( myTransform.right * 0.5f ), out hit,
wallAvoidDistance ))
{
When the Raycast function finds an obstacle, the variable obstacleHitType is set to 1.
This represents an obstacle on the left side. At the end of this section, the value of obstacle-
HitType will form the return value for the function:
// obstacle
// it's a left hit, so it's a type 1 right now
// (though it could change when we check on the
// other side)
obstacleHitType=1;
}
Search WWH ::




Custom Search