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!

Answers


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
}

Need Your Help

Ajax Chat front end supporting IRC backend

ajax chat irc

I am looking for an ajax web chat solution that supports IRC back end. Basically I have my own IRC server. I want to configure an ajax web chat solution to connect to it. I found tons of ajax web c...

Connect to DB and Activites by OOP in PHP

php oop mysqli this

Hi I am having some issues connecting to my DB using OO PHP. My script is below. I have been going at this for a while now. This is just a test script as I am fairly new to OOP. Please don't be har...