Giving enemies the ability to detect and react to your player is a fundamental mechanic that act as the bedrock of enemy AI. This can be as simple as target acquisition to chase or shoot at your player or creating more complex mechanics such as a stealth or cover system. We’ll create a really rudimentary detection mechanic using colliders and triggers.

Start by creating a or opening an existing project, I will be using a the project I’ve been working on for the last few articles. We’ll start by blocking out a simple turret using a few Unity Cubes like so. Be creative, alternatively if you have a model you’d like to use this would be a good time to use it.

In my example I have a few blocks , a large base that will act as the parent object, then childed underneath a turret head and a barrel sticking out of it. That will act as the object we’ll rotate to illustrate the turret’s look direction.

Next we’ll add the detection sensor as child of the Gunhead which is just a simple Unity Cube without the mesh renderer, set the Box Collider to the desired area you want to cover. It is important you set it to Trigger in the Box Collider as that will detect when the player enters range.

Put a Rigidbody on the Turret but mark it as Kinematic that way collisions or gravity will have no effect on it. In order for a object to detect another collider it must have a Rigidbody (you can read more on Rigidbodies here) attached to it to function. Uncheck “Use Gravity” and mark “Is Kinematic” to ensure it isn’t acted on by Gravity or collisions.

Next we’ll make sure the player is tagged with the correct tag which in this case is “Player” so that we can make a comparison check.

Below is the coding logic for the turret, basically it will pan back and forth until the Player steps into it’s radius. Once it does and it detects, the player it will snap to the player until they leave the radius.

Let’s see it in action.

Looking pretty good. A simple but effective enemy detection mechanic. At it’s core it’s really a trigger that detects a target (the player in this case) when it enters it’s view. This should give you the building blocks necessary to craft a more robust detection system with more parameters to better customize it to your game. Until next time, happy coding.