A Coin Trick- Game Dev Series 71

S.J. Jason Liu
4 min readJul 6, 2021

--

Objective: make our player can right click to toss a coin that distracting guards.

Following the setting of guards, there is one that standing still with no patrol route. It is a big challenge to our Player. To make it moves away, we need to create a function to toss a coin for distraction. This would affect to all guards to move toward the position coin dropped.

In this article, we will create the coin tossing function and how to change the movement of guards.

Right click to toss

To toss a coin at the mouse position, we need to create a prefab variable in Player script first to storage the prefab.

The function of right click position is pretty much the same to move our player. We will also use RaycastHit to locate the position, and instantiate the coin prefab at the hit position.

The next is to call all the guards to move toward the coin position.

Send position to guards

We need to get all the gameobject of guards to send the position info. Create an array variable to storage all guards.

Create a new method and find all the guard in scene by searching their tags. Then we can get their script in code.

Now we need to open GuardAI script to receive the coin position by using public method. Before that, create a new Vector3 and a bool variable.

Using these variables in a new public method.

With this bool and Vector3, we can make a movement switch to guards. Adjust the original movement code to an if statement.

Now our guards would head toward the coin when detected. However, it would stuck at the coin position forever. We need to set the bool back to false.

In here I use Invoke to delay the bool switch. With this, the guards should back to their tour after 8 seconds.
Now we can adjust the last line of our Player script.

Last thing is to run this method when we right clicking to toss.

All done! We can distract the guards now!

One shot only

Although we can toss coin to distract, it seems the amount of coin is unlimited!

We should make our Player can only toss one coin.
Create a bool in Player script. Use this bool as a condition to our right click if statement.

After the coin tossed, switch the bool.

That’s it! Player can only throw coin once!

--

--

S.J. Jason Liu

A passionate gamer whose goal is to work in video game development.