Daily progression update —Distracting Guards With a Cointoss
Todays lesson was creating a guard distraction system using a coin that Darren would toss.
First, we figured out how we would throw the coin which was to use the right mouse button, and we essentially used the same code for placing darren and the guards using the raycast hitInfo combo.
The coin would also make a noise. The lesson mentioned to place it into a holder variable that would be played when the throw was initiated, but I figured it would be easier to just attach the audioclip to the coin itself with an Audiomanager and have it play immediately. Same effect, no code!
The code seemed to run well!
There was also an issue of having unlimited coins but that was easily fixed with a boolean called _hasThrowncoin that is set to true after it’s thrown and is checked if it’s false initially to allow the coin toss.
The next challenge was getting all the guards to the scene of the coin once it’s thrown. I knew it had something to do with getting them through Unitys FindObject, but was a bit fuzzy so I peeked ahead and yes, it was GameObject.FindGameObjectsWithTag. A foreach loop was created to cycle through all the guards and set their navmesh agent to be set to where the coin was tossed. Not surprisingly, it took a bit of coding for it to work properly.
A new routine was made called SendAIToDestination that’s called in the same mousebutton 1 click function. We first create an array called guards, and then we find all of them in the game using GameObject.FindGameObjectsWithTag(“Guard1”).
Then we cycle through each guard, access their navmesh agent and script and send our coin position to the guard script so the navmesh can know where to move. The guard also has its own coinPos variable so it can know when to stop when distance checking.
This is the guards code, in the initial if check, we’ve added to see if the cointoss is false, if it is, just walk the normal beat, but in the else statement, when the cointoss is true and the navmesh agent has been given the coins location to move towards, we tell it to give it a buffered distance of 4 units before stopping walking.
BTW, to make things a little simpler, I just created a boolean system of animating the walk. If it’s true, the guards walk, and if not, they don’t.
And AnimateWalk is constantly running under Update().
Next was an easier challenge and that was to trigger Darrens throwing animation when the coin was tossed.
This was achieved easily enough, just set up the throw animation and attach a trigger to it.
and set it when the right mouse button is hit.
Finally, I learned about playing an audio clip without needing an AudioSource with for voice-over triggers:
That’s pretty much all for now. Tomorrow we’ll talk about animating security cameras!