In this recipe, we will implement a behavior that imitates our own ability to evade walls. That is, seeing what we have in front of us that could be considered as a wall or obstacle, and walk around it using a safety margin, trying to maintain our principal direction at the same time.
Avoiding walls
Getting ready
This technique uses the RaycastHit structure and the Raycast function from the physics engine, so it's recommended that you look at the documents for a refresher in case you're a little rusty on the subject.
How to do it...
Thanks to our previous hard work, this recipe is a short one:
- Create the AvoidWall behavior derived from Seek:
using UnityEngine; using System.Collections; public class AvoidWall : Seek { // body }
- Include the member variables for defining the safety margin and the length of the ray to cast:
public float avoidDistance; public float lookAhead;
- Define the Awake function to set up the target:
public override void Awake() { base.Awake(); target = new GameObject(); }
- Define the GetSteering function required for future steps:
public override Steering GetSteering() { // body }
- Declare and set the variable needed for ray casting:
Steering steering = new Steering(); Vector3 position = transform.position; Vector3 rayVector = agent.velocity.normalized * lookAhead; Vector3 direction = rayVector; RaycastHit hit;
- Cast the ray and make the proper calculations if a wall is hit:
if (Physics.Raycast(position, direction, out hit, lookAhead)) { position = hit.point + hit.normal * avoidDistance; target.transform.position = position; steering = base.GetSteering(); } return steering;
How it works...
We cast a ray in front of the agent, and when the ray collides with a wall, the target object is placed in a new position, with consideration given to its distance from the wall and the safety distance declared, delegating the steering calculations to the Seek behavior; this creates the illusion of the agent avoiding the wall.
There's more...
We could extend this behavior by adding more rays, such as whiskers, in order to achieve better accuracy. Also, it is usually paired with other movement behaviors, such as Pursue, using blending:
See also
For further information on the RaycastHit structure and the Raycast function, please refer to the official documentation available online at these links: