Creating A Coin Distraction

I have always found tossing some items (stones etc.) to distract some enemy characters interesting. The first game came into my mind was Far Cry series.

Today was a good day, in which I learned some tricks to make the Agents move to the coin toss position.

As the game I am building right now is a stealth game, I am going to try to explain the way how you can add a distraction functionality to your game. Well, to instantiate the coins at the right click location is pretty easy, but making the AI agents to move towards the coin is not.

Just like on the Point & Click movement (click for the article), we can make the player to coss a coin at the right click location with the coding below. The idea is to send a ray at the right click location, and instantiate the coin if it collides. To block the player from instantiating numerous coins, I have added a cointossed boolean which will block the player to toss new coins after tossing one. Certainly, we can easily adjust it to the number of coins according to our desire simply.

Now, the hard part. We have successfully tossed our coin, how are we going to make the enemy agents to deroute from their current waypoints and move towards the coin location? Since the agents are moving on a Nav Mesh systeme, there is a need to find a way to set their destination to the coin’s position.

I have 3 different enemy agents with the same tag on the scene, which are moving on different waypoints. To reach the array of game objects with the same tag we can simply use FindGameObjectsWithTag.

Once that we have referenced the each guard game object, we can now reach to their components one by one.

Since hitinfo value will not be reached outside of the method that it has been assigned, we need to create a new function with a Vector3 parameter, which will take the hitinfo as the input parameter once we tossed the coin.

Since the guards are checking and updating their destination on every frame, we need to add a bool to get them out of the loop if the coin is tossed. Simply add a public bool for coin tossed to the AI Agent script, so that we can manipulate it outside of it(from player script).

To avoid any errors, make sure that you don’t have any other game objects with the same tag.

And that’s actually all. Just don’t forget to add the necessary line to turn the animator on the guards to the idle state once they reach the coin location.

And here’s a shot from the game :)

Unity Developer