With this recipe, we show you how to use the actual speed of the character to update the value of a float
variable. Once the values grow beyond the 0.5
threshold we defined in the Animator window, the Run clip is played.
Open the script named Char_Animator and be ready to edit the new lines we need to add the controls to switch between the walk and run clips.
private Transform charRef;
Start()
function, we initialize our Transform variable:charRef = this.GetComponent<Rigidbody>();
Rigidbody
function in the formula is a built-in component of Unity that allows physics to affect the game object. We will discuss this in a later chapter.Update()
function of the script to make the fSpeed
parameter equal to the character's horizontal speed, so that the proper animation clip is played depending on how fast the character is moving:charAnimator.SetFloat("fSpeed", charRef.rigidbody.velocity.z);
if()
cycle to check whether the character is playing the Idle2 animation, and in such a case, we reset the fWait
parameter to 0.0
.As you can see, coding the transition based on a float
parameter was pretty easy, thanks to that Rigidbody
component that stores the actual speed of a game object. We will discuss the Rigidbody component in detail in Chapter 4, Taking Control; what is important here is that we can equal the float
parameter to the actual speed of the character to switch between clips.
There is another relevant method available with Animators that is worth a mention, called GetCurrentAnimatorStateInfo
.
This method takes an int
parameter to specify the animator layer we are addressing to, which in our case is 0
, as we are only using one layer of animations for the character.
GetCurrentAnimatorStateInfo
has a method of its own, called IsName
, which allows you to check which animation clip is actually playing through a string parameter with the actual clip name.
The instruction would read like this:
charAnimator.GetCurrentAnimatorStateInfo(int).IsName("string");
Checking the actual state (animation clip) a game character is performing at any moment can be useful, for example, if you plan to chain clips together and allow the second to be triggered only if the first is already playing. Can you imagine a game situation where you would need this?
18.222.93.132