NPCs Raycasting for Line of Sight

First, let’s remind ourselves about aiming rays and casting rays.

Rays are made up of two parts:

  • Origin

  • Direction

We can make Ray variables in a script in the usual variable declaration section (the top of the class):

Typically we also declare a variable to store information about what a ray hits here too. That variable is of type RaycastHit.

We can then define what the origin and direction of the ray will be wherever we need to:

Note that declaring a ray is only aiming. To actually ‘fire’ we need to cast the ray. This is completed using the Physics.Raycast() function.

This function requires a ray to shoot, alongside somewhere to save information about what that ray intersects with:

Remember, it’s always useful to wrap Physics.Raycast() in an if() statement, as no code will run if it hits nothing.

As usual, the most efficient way to check if a ray hit a certain object is to look at that object’s type in the RaycastHit variable you saved.

So we now have the next problem then. How do we get a ray to shoot towards another object? Luckily we have a function built-in to the transform component called LookAt(). This function simply makes a game object face another game object. We likely need to save a public variable of type GameObject then, for the thing we want to always be looking at:

Then we can call LookAt() in the Update() loop:

Another trick I like to use is to have an empty object, parented to the object that is ‘looking’ so to speak, that is constantly rotating towards the object it’s looking for. Then, we use that object’s direction for our ray’s direction. This means that an enemy isn’t just automatically going to face the player even when they don’t see them. We just need to make an empty game object in the inspector, and then make a reference to it in the script:

Finally, we can change our ray to that object’s direction, not this object’s direction.

Finally, we can also do some creative things to create a vision cone. Specifically, we can only consider that our enemy can see the player when the empty game object isn’t rotated too far. Essentially, if that object is rotating past a certain number, it implies that the player is behind that ‘searching’ character, and therefore shouldn’t be able to see it. We can do this in our if() statement where we check if we have hit a certain tag:

Essentially, what this means is, if a straight line coming from an object hits the player, and that object isn’t rotated too far, back, you can see the player.

Activities

Can you build a 'security camera' object that, when it can see the player, makes an enemy AI Agent pathfind towards you?

Can you make an enemy run away from you if it can see you?

Reference Script

Last updated