Polling the Current Input State

From Slick2D Wiki
Jump to: navigation, search

Polling the input allows you to check the state of the input devices at a given momemnt in time. This suitable for cases where you're expecting the player to hold a button/key down while something happens in game - for instance, hold cursor left to run left. The key can be simply polled from the game loop. However, the downside is that if the game loop isn't running quickly enough the input may miss changes.. for instance if the user were to tap left and the tap occured while your game was rendering it may be missed. When short lived input is expected it may be more suitable to use the event based input.

Mouse[edit]

Mouse input can be checked by using the isMouseButtonDown() method to check the buttons and getMouseX() and getMouseY() to check positional information. Note that the mouse position has it's origin (0,0) in the top left hand corner of the display unlike OpenGL. This is down to author discretion rather than any desperate need.

Keyboard[edit]

Keyboard state can be passed using the isKeyDown() method on the Input class. The identifier of the key to check should be supplied and these identifiers are defined within the Input class. For instance to check if space is pressed you do the following:

inputInstance.isKeyDown(Input.KEY_SPACE);

Controllers[edit]

An arbitrary number of gamepads or joysticks are supported. At initialization the controllers are detected and assigned IDs. The controller directional and button state can be polled using the isButtonXPressed() methods and the isControllerXXXX() for directional control. For instance if we'd like to check if the controller was pushed left and button 1 was pressed the following code can be used:

// note we're specifying controller ID zero here, using BasicGame you can 
// check all the controller is one sweep
if (input.isControllerLeft(0) && input.isButton1Pressed(0)) {
  // fire the big guns here!
}

See Also[edit]