Using Input.GetAxis instead of Input.GetKey

Why not use Input.GetAxis instead of Input.GetKey, as in the previous module?

        if (Input.GetAxis("Horizontal") != 0)
        {
            transform.Rotate(Vector3.forward * Time.deltaTime * RotationThrust * Input.GetAxis("Horizontal") * -1);
        }

Can’t tell for sure, but I think the reason to do that is because of this line of code:

Input.GetAxis("Horizontal") != 0

You should never, and I mean NEVER, compare floats to 0, floats might not always return 0, they might end up with a value of 0.0000143 or something like that, that’s not 0 and it will cause a lot of unexpected behaviours. Always keep that in mind when using floats.

Good call on floats, I think that we don’t actually need the if statement at all, we could just unconditionally call Rotate:

transform.Rotate(Vector3.forward * Time.deltaTime * RotationThrust * Input.GetAxis("Horizontal") * -1);
1 Like

Yeah, you could totally do that, but there’s a bug with rotation that Rick fixes later, not sure if it can be solved without the if statement.

That’s a good point, we need to turn physics off and then back on… so perhaps we could check for the axis value and only rotate if Math.Abs(Input.GetAxis(“Horizontal”)) > SOME_THRESHOLD…

The reason I like Input.GetAxis is that it can work with a controller or other ways of input (doesn’t have to be the keyboard, while on the keyboard it works with both AD and LEFT/RIGHT keys which is nice).

i just did

private void PlayerRotation()
{
transform.Rotate(Vector3.forward * -Input.GetAxis(“Horizontal”) * rotationSpeed * Time.deltaTime);
}

Privacy & Terms