Working with Unity FSM
Continuing from the previous article, we will finish up our FSM by adding an Attack State so that our Ai Sphere will stop at every waypoint and pause for a few seconds before moving onward to the next waypoint.
In order to do this we will need to swap from the walking state to the Attacking state, then stop our Ai Agent from moving. Then create a local bool which will tell us whenever the Ai has been swapped to Attack state or isn’t in Attack state so we can control our wait timer via Enumerator before we can resume our walking state.
First we are going to create one new Local bool variable and one local float variable. The bool is going to be the trigger condition for the attack timer. And the Attack Seconds is the timer which the Ai needs to wait before resuming its walking rotation.
Next we are going to create a new private method called “Attacking” which will be responsible to for swapping the Enum State from Jumping/Walking to Attacking. We will also change the private bool from false to True.
The Attacking method needs to be triggered before we can start the contents of the attacking function. Where we call the Attack function is important. Since we want the Attack method to be triggered whenever we are close to the waypoint we can actually place the Attack method inside the Calculate Movement script since we are also tracking the distance between the AI and waypoints.
By doing it like this, the Ai will only stop and attack whenever the AI sphere is near the waypoints.
To determine what actions are done within the Attacking state, we will need to create one more private method. In this Calculate Attack method we are going to on trigger the conditions whenever the bool of “is Attacking” is set to true. We don’t want the AI Sphere to continuous attack, and we only want the AI sphere to just attack once.
As you can see, we are going to start a Coroutine when the bool “is Attacking” is set to true and the AI is in the Attacking state.
After creating the new Enumerator we are going to state that the Agent is stopped and all movement will be paused.
Then we are going to wait for the Attack Seconds which we setup as a local float way back. This is done so that we can freely alter the timing within the inspector in Unity.
Once the wait timer has been met, we are going to reverse everything and also set the current state back to walking.