My journey becoming a Unity game developer: Coin Distraction
Objective: Setup the player to use a coin distraction system. Also, be able to keep the player to using only one coin to distract the guards.
We’re going to use a coin to distract the guards and give Darren a chance to get past them on their patrols. There is 2 ways we can set the player up to toss a coin in a direction we will want the guards to go to.
First way we will open the Player script, and create a new variable that will be used as a reference to the Type Game Object coin prefab. Create another variable that will also be a reference for a Type Audio Clip coin sound effect.
Then inside of the Update() function, move the rayOrigin and hitInfo variables outside of the IF GetMouseButtonDown() condition as we will need access to these 2 variables for the mouse right-click button. Create an IF condition to check if the mouse right-click button is down. Create another IF condition to check if the Raycast is coming from the Main Camera to the object it hits giving us its information.
If the conditions are met, instantiate the coin prefab to the point where the ray hits onscreen without any rotation added. After instantiating the coin, we will use the Audio Source to play the audio clip at the point where the mouse is right-clicked using the coin audio clip hitting the ground at the point where the mouse pointer is clicked.
Click on the Player game object and go to the Player script component. Drag the coin prefab and coin drop audio clip into their respective slots created in the script. Check to make sure the coin prefab has a collider on it to land on the floor properly.
When we play the game, we will see the coins appearing where the pointer is right-clicked at. If the coins are not visible enough to be seen, go to the Coin prefab and adjust its Scale values.
The second way we can make the coins play is to create a new Coins script. Inside this script, use the same variables from the Player script for the coins and the code for the right-click mouse button in the Update() function as well.
Attach the Coins script to the Player game object. Then drag the coin prefab and coin drop audio clip into its slots in the Coins script component.
One last thing is we want to limit the player to being able to toss the coin one time only. Create a new Bool variable to check if the coin has been tossed setting it to False. Then check IF the right-click mouse button is pressed AND if the coin tossed is still False. If those conditions are met, above instantiating the coin, set coin tossed is True inside the IF Raycast condition.
Play the game to see that we can only toss out one coin where we right-click.
Whichever way you prefer to setup the Coin Distraction is okay. Next time we will create AI for the guards to go where the coin appears.