So I am a total noob at Unity and C# scripting. But this is for my assignment.
The situation currently is that I have an animation for my character that goes from idle > jogging > running. Running is triggered by pressing LeftShift, however currently, the animation change is instantaneous rather than a gradual change.
I’m using Mechanim for these animations, and when attempting to deal with this issue, it’s mainly to do with the scripting. Basically, I’m trying to get it so that when the player presses left shift, there is a gradual change from jogging to running. At the moment, the change is sudden, or rather not what it should be…
float h = Input.GetAxis ("Horizontal");
float v = Input.GetAxis ("Vertical");
float blendAnimationSpeed = 0.0f;
if (Input.GetKey (KeyCode.LeftShift))
{
blendAnimationSpeed += Time.deltaTime;
v = blendAnimationSpeed;
}
animator.SetFloat ("Forward", v);
animator.SetFloat ("Strafe", h);
I’m definitely certain I’m missing something very simple, and I just cannot figure it out. I have the movement (physically) sorted out, it’s just the animation itself. So what else am I missing in addition to my clear misunderstanding?
TL;DR How do I get a gradual change from jogging to running? Even better so that I can the speed of the change?
Thanks.
Input.GetAxis (“Vertical”);. I guess you are using a keyboard for these inputs, if so: the button press will give you an instant 1 value for pressed and 0 for released. you want to gradually change the V & H value based on this input. an example would be:
Define these variables at the start of your class (so outiside of update)
float v = 0;
float accelaration = 0.3f;
float deceleration = 0.65f;
float maxMoveSpeed = 1.0f;
then inside your Update()
if(Input.GetAxis ("Vertical") > 0)
v = Mathf.MoveTowards(v, maxMoveSpeed, accelaration * Time.deltaTime);
else
v = Mathf.MoveTowards(v, 0, deceleration * Time.deltaTime);
this will Increase and Reduce V overtime, based on wether you have a button input. then you just pass this V value to the animator as you are already doing.
When running you could use a diffrent “maxRunSpeed” instead, and maybey also diffrent accel - decel vlaues to make it look better.
In your Mechanim implementation, under what condition your character transits from walking to jogging to running? I’m assuming it’s based on “Forward” value. You can set it this way:
- if Forward is equal to 1, then walk
- if Forward is between 1 and 2, then
jog
- if Forward is equal to 2, then run
And then use this script instead:
float h;
float v;
float blendAnimationSpeed;
void Update()
{
h = Input.GetAxis ("Horizontal");
v = Input.GetAxis ("Vertical");
if (Input.GetKey (KeyCode.LeftShift))
{
blendAnimationSpeed += Time.deltaTime;
v = blendAnimationSpeed;
} else {
blendAnimationSpeed = 0.0f;
}
animator.SetFloat ("Forward", v);
animator.SetFloat ("Strafe", h);
}
Basically, you need to define your variables outside of Update method.