LibGDX Tutorial Part 14: Gamepad support

Today we are going to look at adding game pad support into LibGDX, specifically the XBox 360 controller.  Why the Xbox 360 controller?  Well, it’s the controller that I ( and 90% of other PC gamers it seems ) own.  You should be able to modify the following to work with any gamepad, but it’s left as an exercise for the viewer.

There are two things we need to be aware of right away.  First, Controller support is via an extension, so when you are creating your project, you need to select Controller like so:

libgdxController

Next, LibGDX doesn’t actually support the 360 controller out of the box, it only ships with mappings for the Ouya controller.  Fortunately, thanks to the power of Google, I found someone else to do the work for us!  There is a code sample midway through this thread.  Download the included source and save it to a file named XBox360Pad.java.  Yes, case is important.  So it should look like this:

package com.gamefromscratch;

import com.badlogic.gdx.controllers.PovDirection;

// This code was taken from http://www.java-gaming.org/index.php?topic=29223.0
// With thanks that is!

public class XBox360Pad
{
    /*
     * It seems there are different versions of gamepads with different ID 
     Strings.
     * Therefore its IMO a better bet to check for:
     * if (controller.getName().toLowerCase().contains("xbox") &&
                   controller.getName().contains("360"))
     *
     * Controller (Gamepad for Xbox 360)
       Controller (XBOX 360 For Windows)
       Controller (Xbox 360 Wireless Receiver for Windows)
       Controller (Xbox wireless receiver for windows)
       XBOX 360 For Windows (Controller)
       Xbox 360 Wireless Receiver
       Xbox Receiver for Windows (Wireless Controller)
       Xbox wireless receiver for windows (Controller)
     */
    //public static final String ID = "XBOX 360 For Windows (Controller)";
    public static final int BUTTON_X = 2;
    public static final int BUTTON_Y = 3;
    public static final int BUTTON_A = 0;
    public static final int BUTTON_B = 1;
    public static final int BUTTON_BACK = 6;
    public static final int BUTTON_START = 7;
    public static final PovDirection BUTTON_DPAD_UP = PovDirection.north;
    public static final PovDirection BUTTON_DPAD_DOWN = PovDirection.south;
    public static final PovDirection BUTTON_DPAD_RIGHT = PovDirection.east;
    public static final PovDirection BUTTON_DPAD_LEFT = PovDirection.west;
    public static final int BUTTON_LB = 4;
    public static final int BUTTON_L3 = 8;
    public static final int BUTTON_RB = 5;
    public static final int BUTTON_R3 = 9;
    public static final int AXIS_LEFT_X = 1; //-1 is left | +1 is right
    public static final int AXIS_LEFT_Y = 0; //-1 is up | +1 is down
    public static final int AXIS_LEFT_TRIGGER = 4; //value 0 to 1f
    public static final int AXIS_RIGHT_X = 3; //-1 is left | +1 is right
    public static final int AXIS_RIGHT_Y = 2; //-1 is up | +1 is down
    public static final int AXIS_RIGHT_TRIGGER = 4; //value 0 to -1f
}

Now let’s jump right in with a sample:

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.controllers.Controller;
import com.badlogic.gdx.controllers.ControllerListener;
import com.badlogic.gdx.controllers.Controllers;
import com.badlogic.gdx.controllers.PovDirection;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;

public class Gamepad extends ApplicationAdapter implements ControllerListener {
   SpriteBatch batch;
   Sprite sprite;
   BitmapFont font;
   boolean hasControllers = true;
   String message = "Please install a controller";

   @Override
   public void create () {
      batch = new SpriteBatch();
      sprite = new Sprite(new Texture("badlogic.jpg"));
        sprite.setPosition(Gdx.graphics.getWidth()/2 -sprite.getWidth()/2,
                           Gdx.graphics.getHeight()/2-sprite.getHeight()/2);

        // Listen to all controllers, not just one
        Controllers.addListener(this);

        font = new BitmapFont();
        font.setColor(Color.WHITE);


        if(Controllers.getControllers().size == 0)
        {
            hasControllers = false;
        }
    }

   @Override
   public void render () {
      Gdx.gl.glClearColor(0, 0, 0, 0);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
      batch.begin();
        if(!hasControllers)
            font.draw(batch,message,
                    Gdx.graphics.getWidth()/2 - font.getBounds(message).width/2,
                    Gdx.graphics.getHeight()/2 - font.getBounds(message).height/2);
        else
          batch.draw(sprite, sprite.getX(), sprite.getY(),sprite.getOriginX(),sprite.getOriginY(),
                    sprite.getWidth(),sprite.getHeight(),
                    sprite.getScaleX(),sprite.getScaleY(),sprite.getRotation());
      batch.end();
   }

    // connected and disconnect dont actually appear to work for XBox 360 controllers.
    @Override
    public void connected(Controller controller) {
        hasControllers = true;
    }

    @Override
    public void disconnected(Controller controller) {
        hasControllers = false;
    }

    @Override
    public boolean buttonDown(Controller controller, int buttonCode) {
        if(buttonCode == XBox360Pad.BUTTON_Y)
            sprite.setY(sprite.getY() + 1);
        if(buttonCode == XBox360Pad.BUTTON_A)
            sprite.setY(sprite.getY()-1);
        if(buttonCode == XBox360Pad.BUTTON_X)
            sprite.setX(sprite.getX() - 1);
        if(buttonCode == XBox360Pad.BUTTON_B)
            sprite.setX(sprite.getX() + 1);

        if(buttonCode == XBox360Pad.BUTTON_LB)
            sprite.scale(-0.1f);
        if(buttonCode == XBox360Pad.BUTTON_RB)
            sprite.scale(0.1f);
        return false;
    }

    @Override
    public boolean buttonUp(Controller controller, int buttonCode) {
        return false;
    }

    @Override
    public boolean axisMoved(Controller controller, int axisCode, float value) {
        // This is your analog stick
        // Value will be from -1 to 1 depending how far left/right, up/down the stick is
        // For the Y translation, I use a negative because I like inverted analog stick
        // Like all normal people do! 😉

        // Left Stick
        if(axisCode == XBox360Pad.AXIS_LEFT_X)
            sprite.translateX(10f * value);
        if(axisCode == XBox360Pad.AXIS_LEFT_Y)
            sprite.translateY(-10f * value);

        // Right stick
        if(axisCode == XBox360Pad.AXIS_RIGHT_X)
            sprite.rotate(10f * value);
        return false;
    }

    @Override
    public boolean povMoved(Controller controller, int povCode, PovDirection value) {
        // This is the dpad
        if(value == XBox360Pad.BUTTON_DPAD_LEFT)
            sprite.translateX(-10f);
        if(value == XBox360Pad.BUTTON_DPAD_RIGHT)
            sprite.translateX(10f);
        if(value == XBox360Pad.BUTTON_DPAD_UP)
            sprite.translateY(10f);
        if(value == XBox360Pad.BUTTON_DPAD_DOWN)
            sprite.translateY(-10f);
        return false;
    }

    @Override
    public boolean xSliderMoved(Controller controller, int sliderCode, boolean value) {
        return false;
    }

    @Override
    public boolean ySliderMoved(Controller controller, int sliderCode, boolean value) {
        return false;
    }

    @Override
    public boolean accelerometerMoved(Controller controller, int accelerometerCode, Vector3 value) {
        return false;
    }
}

Amazingly enough, LibGDX actually manages to support controllers in their HTML target, so below is the following code running.  Maybe.

No iFrame Support

(Open in new window)

Of course, this is gamepad support in HTML5 we are talking about here, so it will only work in a very small subset of browsers and certainly may not work as expected.  However, the fact it runs at all is rather astonishing.  You may need to open the examples in a separate window using the link above to get it to work correctly.  No worries though, on a Desktop target, the above code works perfectly.

In this sample we are taking an event driven approach.  That is, as the controller is updated, it pushes a variety of events to our class.  This is done via the ControllerListener interface.  As you can see from the override’s, there is a great deal of functionality ( motion, sliders, etc ) that is OUYA specific.  Of interest to us are buttonDown, axisMoved and povMoved.  buttonDown is called predictably enough when one of the controller buttons is pressed, this includes face buttons, select, start and the bumpers, but not the triggers.  axisMoved is called for either of the analog sticks, and perhaps confusingly at first, the triggers are moved.  The reason triggers are supported this way is do the the fact there is a range of values instead of just a binary option like when dealing with buttons.  The amount the trigger is depressed is the range along the trigger axis.  Finally there is povMoved, this is your DPad, which really is just a set of 4 buttons.  One last thing to note here… the disconnect and connect events simply never fired for me, the logic may be OUYA specific.

You may notice however that movement using the analog stick is jerky as hell.  This is because event driven approach isn’t really ideal for analog controls.  You have two options here.  Instead of updating the controls each time an event is fired, you update a flag and apply some smoothing logic, to keep movement between events smooth.  Or, much easier, you use polling instead.  Let’s take a look at how you can poll controls in LibGDX.

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.controllers.Controller;
import com.badlogic.gdx.controllers.Controllers;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class Gamepad2 extends ApplicationAdapter {
    SpriteBatch batch;
    Sprite sprite;
    Controller controller;
    BitmapFont font;
    boolean hasControllers = true;
    String message = "Please install a controller";

    @Override
    public void create () {
        batch = new SpriteBatch();
        sprite = new Sprite(new Texture("badlogic.jpg"));
        sprite.setPosition(Gdx.graphics.getWidth()/2 -sprite.getWidth()/2,
                Gdx.graphics.getHeight()/2-sprite.getHeight()/2);

        font = new BitmapFont();
        font.setColor(Color.WHITE);

        if(Controllers.getControllers().size == 0)
        {
            hasControllers = false;
        }
        else
            controller = Controllers.getControllers().first();
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0, 0, 0, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        if(!hasControllers)
            font.draw(batch,message,
                    Gdx.graphics.getWidth()/2 - font.getBounds(message).width/2,
                    Gdx.graphics.getHeight()/2 - font.getBounds(message).height/2);
        else {
            // Update movement based on movement of left stick
            // Give a "deadzone" of 0.2 - -0.2, meaning the first 20% in either direction will be ignored.
            // This keeps controls from being too twitchy
            // Move by up to 10 pixels per frame if full left or right.
            // Once again I flipped the sign on the Y axis because I prefer inverted Y axis controls.
            if(controller.getAxis(XBox360Pad.AXIS_LEFT_X) > 0.2f  || 
                    controller.getAxis(XBox360Pad.AXIS_LEFT_X) < -0.2f)
                sprite.translateX(controller.getAxis(XBox360Pad.AXIS_LEFT_X) * 10f);
            if(controller.getAxis(XBox360Pad.AXIS_LEFT_Y) > 0.2f  || 
                    controller.getAxis(XBox360Pad.AXIS_LEFT_Y) < -0.2f)
                sprite.translateY(controller.getAxis(XBox360Pad.AXIS_LEFT_Y) * -10f);

            // Poll if user hits start button, if they do, reset position of sprite
            if(controller.getButton(XBox360Pad.BUTTON_START))
                sprite.setPosition(Gdx.graphics.getWidth() / 2 - sprite.getWidth() / 2,
                        Gdx.graphics.getHeight() / 2 - sprite.getHeight() / 2);
            batch.draw(sprite, sprite.getX(), sprite.getY(), sprite.getOriginX(), sprite.getOriginY(), 
                    sprite.getWidth(),sprite.getHeight(), 
                    sprite.getScaleX(), sprite.getScaleY(), sprite.getRotation());
        }
        batch.end();
    }
}

Now here is this code running ( sorta, maybe )

No iFrame Support

(Open in new window)

Here you can see we simply poll the controller for it’s status each frame.  getAxis returns the amount the controller is depressed in either direction along that axis as a value from –1 to 1.  getButton on the other hand returns a boolean representing if the button is currently pressed or not.  One important thing to keep in mind here, this code is incredibly fragile.  LibGDX controller supports multiple controllers, but in this case I simply check to see if any exist and use the first one I can find.  This means if you have multiple controllers plugged into your PC, all but the first one will be ignored.  Second, this code simply assumes the controller is an XBox 360 controller, no idea what will happen if another controller is used instead.  Most likely the worst case scenarios is buttons might be mismapped or non-existent.

The only other thing of note ( and mentioned in the comments ) is I applied a dead zone value of –0.2 to 0.2 for each analog stick.  This keeps the controller from being overly twitchy and from moving when the user would think the control should be still.  Generally this dead zone value is what you would configure via a sensitivity setting in your game’s settings.  I also flipped the Y axis value because, well, that’s the way it should be! 🙂

Previous PartTable Of ContentsNext Part

Scroll to Top