- Home /
Input Lag in Animation Script
In the Editor and after building the game on Very-Low Quality (although I can easily run max quality), whenever I press a button, it takes maybe 300ms to actually register the input. And when I tap semi-quick my sprite moves but doesn't animate.
I'm pretty new and am tired of looking for so long so I posted here. The problem seems to be that it's taking a while for my animator to receive the boolean (double-checked in animator window).
Oh, and not to forget, my movement script is not affected by this problem although it also uses Input.GetAxis. However, it is a one-liner.
public class RunningAnimation : MonoBehaviour
{
public bool isRunning;
public Animator anim;
bool flipX;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
float moveDirection = Input.GetAxis("Horizontal");
switch (moveDirection)
{
case 0:
isRunning = false;
break;
case 1:
isRunning = true;
flipX = false;
break;
case -1:
isRunning = true;
flipX = true;
break;
}
anim.SetBool("isRunning", isRunning);
this.gameObject.GetComponent<SpriteRenderer>().flipX = flipX;
}
}
Answer by Llama_w_2Ls · Feb 24, 2021 at 02:45 PM
Input.GetAxis returns a value between -1 and 1. As you hold a key on your keyboard, the value increases up to 1, using smoothing, to produce natural movement. The issue here is, your switch statement only works when the cases are 0, 1 and -1. As I said, it returns a value between -1 and 1 and does take some time to get there. The input lag isn't the problem, but how you are reading the value.
I suggest doing some rounding to get the input immediately, for example, right before your switch statement, you could write:
float moveDirection = Input.GetAxis("Horizontal");
// Rounds values to -1, 0 or 1
if (moveDirection > 0)
moveDirection = 1;
else if (moveDirection < 0)
moveDirection = -1;
WHAAT?? It's interpolated??? I would have not thought at all. Well, of course now I'm realizing that's probably for people using controllers. Anyway, whatever. Works like a charm! Thank you!
You can also use Input.GetAxisRaw() if you do not want any interpolation.
Well, it's been over a year so I know that now, but I guess that will be useful for any noobs who see this in the future.
Also, using GetAxisRaw() worked much better for most projects. Thank you for pointing it out
Your answer
Follow this Question
Related Questions
Input returns 0 until released and pressed again if held down before start of scene 0 Answers
Input.GetAxis normal behaviour when both axis inputs active? 0 Answers
Smooth value in Input System 0 Answers
Brake on wheel collider "slips" 1 Answer
Joystick Input - "3rd Axis" etc, not sure what works/doesn't 1 Answer