Skip to content

Listening to Inputs from a Gamepad

Ralph Niemitz edited this page Mar 30, 2018 · 3 revisions

Works the same as listening to mice.

There may be some differences in button layout were an A button can only be checked with GamepadEvent.BUTTON_X, but this should be really rare. XInput devices are currently limited. See the related page to DirectInput and XInput.

Example for an implementation of GamepadListener

public class Adapter implements GamepadListener {

	@Override
	public void onAnalogStickPush(GamepadEvent event) {
	
		int stick = event.getAnalogStick();
		Direction direction = event.getDirection();
		float intensity = event.getIntensity();
		
		if(stick == GamepadEvent.ANALOG_STICK_LEFT) {
		
			System.out.println("The left analog stick was pushed into the direction " + direction.toString() + " with an intensity of " + intensity);
		
		} else if(stick == GamepadEvent.ANALOG_STICK_RIGHT) {
		
			System.out.println("The right analog stick was pushed into the direction " + direction.toString() + " with an intensity of " + intensity);
		}
	}
	
	@Override
	public void onButtonPress(GamepadEvent event) {
	
		System.out.println("Pressed " + event.getButton());
	}
	
	@Override
	public void onButtonRelease(GamepadEvent event) {
	
		System.out.println("Released " + event.getButton());
	}
	
	@Override
	public void onPOVPress(GamepadEvent event) {
	
		System.out.println("POV pressed in direction " + event.getDirection());
	}
	
	@Override
	public void onPOVRelease(GamepadEvent event) {
	
		System.out.println("POV released for direction " + event.getDirection());
	}
}

Example for listening to all gamepads

DeviceManager.create();
DeviceManager.addGamepadListener(new Adapter());
DeviceManager.getGamepads().forEach(Gamepad::startListening);

// YOUR CODE

DeviceManager.destroy();

Example for listening to an individual gamepad

DeviceManager.create();
List<Gamepad> gamepads = DeviceManager.getGamepads();
Gamepad myGamepad = gamepads.get(0); // the first gamepad
myGamepad.addGamepadListener(new Adapter());
myGamepad.startListening();

// When we listen to a single gamepad, we can ask which buttons are currently down.
boolean isXDown = myGamepad.isButtonDown(GamepadEvent.BUTTON_X);

// YOUR CODE

DeviceManager.destroy();

Related