This article will show how to create a distraction that the Player can use to lure the guards from a previous article away from their movement pattern allowing the Player to get by them.
The Player script needs to use the System namespace to use an Action Delegate for the guards to subscribe to know when the coin has been thrown and the coin’s location. For variables, we need one for the coin Prefab to spawn, a second for the coin sound to play, a third for the Layer the Raycast will register hits for so the coin lands flat on the floor, and finally a bool so the Player can only use the coin throw once.
When the right mouse button is pressed and a coin to be used, we cast a ray from the mouse’s position on the screen for 500 units or until it hits a Collider on the Floor Layer. Then we instantiate the coin and play the coin drop sound at that point, and send out the position to anyone listening.
In Unity, we create the Floor Layer, assign the Floor Collider to it, and hook up the Coin Prefab and coin drop sound to the Player.
In the GuardAI script, we need to add a bool to know when the guard moves to the coin’s position and a float to know if the coin is too far away.
We need to make it so the destination and current index number do not change while the guard moves to the coin’s position. Then once the guard has reached the coin, we call the Coroutine to pause for a moment and stop the walk animation.
After the guard has paused, they will return to the last waypoint and continue their movement pattern by turning the moving to coin bool to false and breaking out of the Coroutine.
The last thing we need is a method that receives the coin’s position, checks the distance to know if the guard should react, sets the guard’s destination to it, changes moving to coin to true, and starts the walking animation. Then subscribe and unsubscribe the method to the Player’s Action Delegate in OnEnable and OnDisable.
The guards now all move to the position the coin is dropped and then return to their regular pattern.