Search code examples
c#animationunity-game-enginecontrollerxbox

Play animation with Xbox controller


I am making a 2d game that can use either the keyboard or an Xbox One controller as movement.

So far, I can move the players and play a running animation, jump animation etc using the keyboard, and I can move using the Xbox controller.

However, I can't play animations with the Xbox controller.

I have this:

void Update()
{
    movement.x = Input.GetAxis("LeftJoystickX") * speed * Time.deltaTime;

            // Orange player movement
            if (orange)
            {
                transform.position += movement;

                if (Input.GetKey(KeyCode.D))
                {
                    ChangeDirection("right");
                    ChangeState(STATE_RUN);
                    transform.position += Vector3.right * speed * Time.deltaTime;
                    if (!onGround)
                        ChangeState(STATE_JUMP);
                }
            }
}

Here, if you use the keyboard, the animations play. If you use the controller, the player moves but the animations don't play. I've tried and narrowed it down to the fact that this piece of code will not evaluate:

if (Input.GetAxis("LeftJoystickX"))

as Input.GetAxis() returns a float and not a bool (?) and therefore cannot be put in an if statement.

I guess what I am asking is, is it possible to detect a direction of a Joystick push from a controller, such as something like Input.GetAxis().joystickPushedRight?

Or better yet, is there a different way I could execute

 if (Input.GetKey(KeyCode.D))
        {
            ChangeDirection("right");
            ChangeState(STATE_RUN);
            transform.position += Vector3.right * speed * Time.deltaTime;
            if (!onGround)
                ChangeState(STATE_JUMP);
        }

But use the joystick instead of Input.GetKey?

Thanks!


Solution

  • Input.GetAxis returns a float between -1 and 1.

    If you take that into account together with a threshold for values close to zero you can determine if you need to go up or down or need to stop.

    Your implementation will look like this:

    const float threshold = 0.05;
    const string axis = "LeftJoystickX";
    if (Input.GetAxis(axis) < -threshold)
    {
      //go left
    } 
    else if (Input.GetAxis(axis) > threshold) 
    {
       //go right
    } 
    else 
    {
       // don't move
    }