Coding the float-based transitions

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.

Getting ready

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.

How to do it...

  1. First of all, we need to add a Transform variable to store a reference to the character in the scene:
    private Transform charRef;
  2. In the Start() function, we initialize our Transform variable:
    charRef = this.GetComponent<Rigidbody>();
  3. The 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.
  4. Next, we can add this single line in the 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);
  5. Next, we add another 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.
  6. Please refer to the following screenshot, where the entire script is displayed, so you can be sure you coded it right:
    How to do it...

How it works...

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's more....

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?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.156.251