- Home /
Inputs and animations interfering with each other
In my game I have it so that when the mouse is pointing on either side of the player and I move the player toward the mouse, it plays a "running forward" animation. On the other hand, when I move the player in the opposite direction of the mouse, it plays a "running backward" animation. So far everything works AS LONG AS I don't try to input two keys at once.
Here's my problem: say I'm pointing my mouse on the right of the player and moving right by holding down the "d" key, it plays "running forward". No problem here. However, if I quickly switch to the "a" key to move left, it still plays "running forward". This obviously has to do with the inputs interfering because everything works nicely if I properly release a key before pressing another. Here's a gif to show you what I mean (I recommend playing in fullscreen). My code:
void Update()
{
//horizontal movement speed
horMove = Input.GetAxisRaw("Horizontal") * moveSpeed;
//position of mouse relative to player
var delta = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
//play running backward
if ((delta.x > 0 && rb.velocity.x < 0) || (delta.x < 0 && rb.velocity.x > 0))
{
animator.SetFloat("SpeedBack", Mathf.Abs(horMove));
}
//play running forward
else if (Mathf.Abs(delta.x) > 0 && Mathf.Abs(rb.velocity.x) > 0)
{
animator.SetFloat("Speed", Mathf.Abs(horMove));
}
else //don't play anything
{
animator.SetFloat("Speed", 0f);
animator.SetFloat("SpeedBack", 0f);
}
}
The conditions in my animator are set up such that "running forward" switches to "running backward" when Speed < 0.01 and SpeedBack > 0.01. And when switching from "running backward" to "running forward", Speed > 0.01 and SpeedBack < 0.01. Any kind of help would be greatly appreciated!
Answer by Optrix · Jul 04, 2019 at 04:08 AM
You don't seem to be setting "Speed" to zero when you set "Speedback" and vice-versa. Make sure you set one to zero if you're setting the other to a positive value.
Unless you've been very careful with your output transitions from your running animations, this means that you'll never stop. Once you start moving, the trigger for your first running animation won't be reset until you come to a complete stop.
You are also basing your logic on velocity but basing your animation values on input. You should be consistent there. Either run forwards when moving forwards, or run forwards when the input asks you to. With your current logic, you're doing an unusual blend of both.
Perhaps you'd be better off with an overall speed - it could be positive for forwards, negative for backwards? This won't have the issue.
Thanks! It works better now. However when quickly switching from "d" to "a" key it switches to "idle" in between "running forward" and "running backward" making my character look like he's jittering for a fraction of a second.
Edit: Never$$anonymous$$d, playing around with transition times and offset transition makes it look smooth!