Animation Parameters

Hi everybody,

I have a basic question about animations. Is it possible to reference animation parameters that are written in javascript? I have code that makes sense, but I just can’t get the animation to play correctly. The way it currently works is that my enemy starts in idle, then his animation plays between walking and running.

I reference variables such as “moveSpeed” in my code in order to trigger the transitions, but dictating that if ‘moveSpeed is greater than 0’ in the ‘Conditions’ portion of the transitions has had no effect on creating the desirable switch from idle to walk, and walk to run etc.

I’m just wondering if these parameters can be referenced in javascript, and if so, what should that look like? I know there is like SetFloat etc. but I am having difficulty manipulating things the way that I envision them

Thank you so much for helping with an explanation and/or a sample code.

Let’s say you have a simple animator controller with two states: Idle and Walk. And you have two transitions:

  1. Idle–>Walk, on condition “moveSpeed greater than 0.01”
  2. Walk–>Idle, on condition “moveSpeed less than 0.01”

If moveSpeed is a float, it’s possible that it won’t exactly equal 0 (it could be 1e-10 or something), so I chose a value close to zero that should work well enough for these transitions.

Then you just need to get a reference to the Animator component and set moveSpeed using SetFloat(). Note that the Animation Parameter “moveSpeed” defined in your animator controller is different from any variable named “moveSpeed” in your script. In the example code below, I used the name “moveSpeed” for both the animation parameter and the script variable to convey that they’re closely related.

var moveSpeed : float = 0;

function Awake() {
    var myAnimator : Animator;
    myAnimator = GetComponent(Animator);
}

function Update() {
    if (Input.GetKey(KeyCode.W)) {
        moveSpeed = 1;
    } else {
        moveSpeed = 0;
    }
    if (myAnimator == null) {
        Debug.LogError("Animator is null!");
    } else {
        myAnimator.SetFloat("moveSpeed", moveSpeed);
    }
}

You could get fancier by using SmoothDamp() to gradually adjust moveSpeed between 0 and 1, rather than changing it abruptly, and then create a blend tree in your animator controller that blends between idle and walk based on the current value of moveSpeed. This will give you a smoother-looking transition. But it’s always best to start simple and build from there.

Also, it’s helpful to select your animator controller while your game is running, so you can see the current value of the moveSpeed parameter, what state is currently active, etc.