Coin Distraction

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.




Unity Developer, Software Engineer, Game Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The concept of recursion

CRUD operations using Apollo-GraphQL

Good News — Advance of APP development

Monitor your Coding Time

The USA TODAY NETWORK’s SRE team’s journey into Docker and Kubernetes. Was it worth it?

Game Dev Digest Issue #58 — Tips You May Not Know

The Linguistics of Programming Languages

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kyle W. Powers

Kyle W. Powers

Unity Developer, Software Engineer, Game Developer

More from Medium

Creating a Physics Based Character Controller from Scratch in Unity

Daily Progression: Player Setup!

Shooting Enemies in Unity.

Unity and Variables❤