Day 78: Coin Distraction

Tyler Smallwood
4 min readAug 14, 2021

--

Objective: Throw a coin and have the guards move to the coin.

We need to throw a coin in an area that the guards need to go so our player can pass.

In our player script we will need to check for our right mouse button input.

As mentioned before we will need to use Raycasting to check to see if we clicked on something.

If we did hit something we need to spawn an item. So therefore we need to get a reference to our coin prefab that will be spawned into the game.

Next will be to instantiate the coin at the point clicked.

To stop the player from spamming the right mouse button, let’s add in a bool to only allow one throw. Let’s create a bool named _hasThrownCoin.

And when we check for the input, let’s make sure _hasThrownCoin is false. If it’s false throw coin and if not do nothing.

To add some life to tossing the coin, let’s create a variable to hold the coin toss sound.

Where we spawn the coin in the game is where we call AudioSource.PlayClipAtPoin();. And where we turn _hasThrownCoin to false.

Now it’s time to make the guards head to the coin. We will need to use a function and call it in the same place as spawning the coin.

Inside our function we will need to round up all the guards and we will need to go through each one. This is done by using a foreach loop.

Before we continue on in the player script, we’ll head over to the GuardAI script and create a function.

Inside this function we’ll call the NavMeshAgent to set the destination to the position of the coin. We will also set a bool to true to let the guardAI know that a coin has been tossed. Next will be to active the walk animation. Lastly, create a variable to save the coinPos.

In our GuardAI’s Update function we check to see if the coin has been tossed.

If it is true, skip the waypoint system and start checking for Distance. If the Distance is less than 2.5f, the guards stop walking.

Now we head back to our Player script and call this function for each guard.

Once that is in there, it is done! Our guards will walk to the coin and stay there.

Thank you for reading and have a wonderful day!

--

--

Tyler Smallwood
Tyler Smallwood

Written by Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer

No responses yet