Unity 3D Code Snippet – Obstacle Detection Component

I’m working to get a good portion of my AI up here (in tutorial form) for my Unity 3D Flight Combat game. Since AI is a bit more complicated than a simple flight script, I’ll put it up piece-by-piece in the form of modular devices you can use for other aspects of the game. Today, I’m going to show you how to give your game a bit more insight (These jokes are killing me).

One thing I’ve learned, back in days of yore, is that when it comes to code, you’re never really the first to do anything – only the first to do it differently. So, to give credit where credit is due, I would like to thank Devon Klompmaker and his Obstacle Avoidance Tutorial for giving me the inspiration. My method is based on his, but I’ve implemented it in a way to make it modular and expandable.

To sum up what we are making here, we are making a game object that will RayCast out along its forward vector, and when it detects an object in it’s cast, it will return true. We’ll also give the component Gizmos so we can observe the sensor in debug.

Setting Up Your Proximity Sensor

  1. Create an empty Game Object. No model, no texture, nothing.
  2. Create a new script, and call it ProximitySensor.
  3. Add the new script to your Game Object

And that’s all you really need to do for the Game Object. One thing to mention is that the objects forward vector is going to be what we’re ray-casting along, so the transform matters here.

Code Walkthrough

The code is pretty short and straightforward. I’ll cover the mechanics of the obstacle avoidance before I cover the gizmos.

First, we define our public variable to indicate the distance the proximity sensor can “see.”

    public float Distance = 20.0f;

From here, we move right on to our Detect function. We will call this function in any script that contains the Proximity Sensor. The logic is real simple: We fire out a RayCast from the proximity senor’s position along its forward vector for a range of Distance. If we hit something that wasn’t our self, we return true (Quick note: I have my script returning a bool, but you can return anything you really want: the hit GameObject, the RayCastHit, and so on).

public bool Detect(out RaycastHit hit)
    {
        if (Physics.Raycast(transform.position, transform.forward, out hit, Distance))
        {
            if (hit.transform != transform)
            {
                Debug.DrawLine(transform.position, hit.point, Color.red);
                return true;
            }
        }

        return false;
    }

That’s it for the game logic! I even have a Debug line draw so we can see it in action! But what about the editor? All you’re going to see if the default transform. That doesn’t help much at all, so lets make our own!

We’re going to use 2 functions that can be overloaded from MonoBehaviour: OnDrawGizmos() and OnDrawGizmosSelected(). OnDrawGizmos will draw anything you want, and you’ll see it in the Scene window (or in the Game window if you have Gizmos active). OnDrawGizmosSelected() will do almost exactly the same, except it will only draw if the object is selected. Easy concept. What we want to do here is draw an icon when we’re viewing it normally, and when it’s selected, we want to see the rays that it’ll draw.

First, lets draw the icon. Go on Google, and find a good Eye Icon. After you find it, create a folder in your project Hierarchy called “Gizmos” and put your icon in there. The code to draw this in your scene is REALLY easy.

    void OnDrawGizmos()
    {
        Gizmos.DrawIcon(transform.position, "eye.png");
    }

Isn’t that the hardest code you’ve ever written? The Gizmos object handles a lot of drawing for you (like most everything else in Unity).

Next, we draw the lines in our OnDrawGizmosSelected() call. This is also really simple.

    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.green;
        Gizmos.DrawRay(transform.position, transform.forward * Distance);
        Gizmos.color = Color.white;
    }

Bam. Easy. There you have it. Simple Obstacle Detection. This will tell you if something is in they way, but it’ll be up to you to apply the logic. The full code is at the bottom. Use it wisely, and, as always, take care.

using UnityEngine;
using System.Collections;

public class ProximitySensor : MonoBehaviour
{
    public float Distance = 20.0f;

    void OnDrawGizmos()
    {
        Gizmos.DrawIcon(transform.position, "eye.png");
    }

    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.green;
        Gizmos.DrawRay(transform.position, transform.forward * Distance);
        Gizmos.color = Color.white;
    }

    public bool Detect(out RaycastHit hit)
    {
        if (Physics.Raycast(transform.position, transform.forward, out hit, Distance))
        {
            if (hit.transform != transform)
            {
                Debug.DrawLine(transform.position, hit.point, Color.red);
                return true;
            }
        }        return false;
    }
}
Advertisements

One thought on “Unity 3D Code Snippet – Obstacle Detection Component

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s