LibGDX Tutorial 4: Handling Input — The mouse and keyboard

In this part we are going to look at how you handle mouse and keyboard input in LibGDX.  There are two ways to go about handling input, by polling for it ( as in… “Has anything happened yet? No, ok…  What about now? No, ok… Now?  Yes!  Handle it” ) or by handling events ( “Hey, you, I’v got this event for you!” ).  Which you go with generally depends on the way you structure your code.  Polling tends to be a bit more resource intensive but at the end of the day that is mostly a non-factor.

Polling the keyboard for input

Let’s jump right in and look at how you poll the keyboard for input.  Here is the code:

package input.gamefromscratch.com;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class InputDemo implements ApplicationListener {
    private SpriteBatch batch;
    private Texture texture;
    private Sprite sprite;
    
    @Override
    public void create() {        
        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();
        batch = new SpriteBatch();
        
        texture = new Texture(Gdx.files.internal("data/0001.png"));
        sprite = new Sprite(texture);
        sprite.setPosition(w/2 -sprite.getWidth()/2, h/2 - sprite.getHeight()/2);
    }

    @Override
    public void dispose() {
        batch.dispose();
        texture.dispose();
    }

    @Override
    public void render() {        
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        
        if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
            if(Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT))
                sprite.translateX(-1f);
            else
                sprite.translateX(-10.0f);
        }
        if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
            if(Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT))
                sprite.translateX(1f);
            else
                sprite.translateX(10.0f);
        }
        batch.begin();
        sprite.draw(batch);
        batch.end();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

Other than the highlighted bit and the translateX method, everything here we have seen before.  Basically we draw a simple sprite centered to the screen and each frame we check to see if the user has pressed the LEFT or RIGHT arrow.  If they have, we check if they also have the left control key held.  If so, we move slowly to the left or right.  If they don’t have Control pressed, we move instead by 10 pixels.

Here is the app, you need to click it first to give it keyboard focus: Thought doest not support iframe

If it doesn’t work in an frame, click here.

Just use the left and right arrows to move the jet. Hold down control to move slowly.  There is no clipping so the sprite can fly way off screen.

In terms of what the new code is doing, the Sprite.translateX method is pretty self explanatory.  It moves the sprite by a certain amount of pixels along the X axis.  There is a translateY method as well, as well as a more general translate method.  The key method in this example is isKeyPressed() member function of the input instance of the global Gdx object.  We used a similar instance member when we accessed Gdx.files.  These are public static references to the various sub-systems GDX depends on, you can read more here.  isKeyPressed is passed a Key value defined in the Keys object and returns true if that key is currently pressed.  As you can see when we later tested if the Control key is also pressed, multiple keys can be pressed at the same time.

Polling the Mouse for input

Now let’s take a look at how you poll the mouse for input.  To save space, this code is identical to the last example, with only the render() method replaced.

public void render() {        
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    
    if(Gdx.input.isButtonPressed(Input.Buttons.LEFT)){
        sprite.setPosition(Gdx.input.getX() - sprite.getWidth()/2,
                Gdx.graphics.getHeight() - Gdx.input.getY() - sprite.getHeight()/2);
    }
    if(Gdx.input.isButtonPressed(Input.Buttons.RIGHT)){
        sprite.setPosition(Gdx.graphics.getWidth()/2 -sprite.getWidth()/2, 
                Gdx.graphics.getHeight()/2 - sprite.getHeight()/2);
    }
    batch.begin();
    sprite.draw(batch);
    batch.end();
}

Here we instead are checking if a mouse button has been pressed using isButtonPressed passing in a button value defined in the Buttons object.  If the left button is pressed, get then poll the mouse position using Gdx.input.getX() and Gdx.input.getY() and set the sprites location to that position.  The math may look a bit overly complicated, why didn’t we simply set the location to the values returned by getX/Y?  There are two reasons.  First, our sprites coordinate is relative to it’s bottom left corner. so if we want to center the sprite, we need to take half the sprites width and height into consideration.  The next complication comes from the fact that LibGDX sets the origin at the bottom left corner, but mouse positions are relative to the top left corner.  Simply subtracting the position from the screen height gives you the location of the mouse in screen coordinates.  We also check to see if the user as hit the right mouse button, and if they have we reposition the jet sprite at the center of the window. Thought doest not support iframe

If it doesn’t work in an frame, click here.

Once again, you need to click within above before it will start receiving mouse events ( depending on your browser ).  Left click and the sprite should move to the location you clicked.  Right click to return to default ( in theory… ), right click behaviour is a bit random in web browsers.

Event driven keyboard and mouse handling

Now we will look at handling the functionality of both of the above examples ( as a single example ), but this time using an event driven approach.

package input.gamefromscratch.com;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class InputDemo implements ApplicationListener, InputProcessor {
    private SpriteBatch batch;
    private Texture texture;
    private Sprite sprite;
    private float posX, posY;
    
    @Override
    public void create() {        
        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();
        batch = new SpriteBatch();
        
        texture = new Texture(Gdx.files.internal("data/0001.png"));
        sprite = new Sprite(texture);
        posX = w/2 - sprite.getWidth()/2;
        posY = h/2 - sprite.getHeight()/2;
        sprite.setPosition(posX,posY);
        
        Gdx.input.setInputProcessor(this);
    }

    @Override
    public void dispose() {
        batch.dispose();
        texture.dispose();
    }

    @Override
    public void render() {        
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

        sprite.setPosition(posX,posY);
        batch.begin();
        sprite.draw(batch);
        batch.end();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }

    @Override
    public boolean keyDown(int keycode) {
        float moveAmount = 1.0f;
        if(Gdx.input.isKeyPressed(Keys.CONTROL_LEFT))
            moveAmount = 10.0f;
        
        if(keycode == Keys.LEFT)
            posX-=moveAmount;
        if(keycode == Keys.RIGHT)
            posX+=moveAmount;
        return true;
    }

    @Override
    public boolean keyUp(int keycode) {
        return false;
    }

    @Override
    public boolean keyTyped(char character) {
        return false;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        if(button == Buttons.LEFT){
            posX = screenX - sprite.getWidth()/2;
            posY = Gdx.graphics.getHeight() - screenY - sprite.getHeight()/2;
        }
        if(button == Buttons.RIGHT){
            posX = Gdx.graphics.getWidth()/2 - sprite.getWidth()/2;
            posY = Gdx.graphics.getHeight()/2 - sprite.getHeight()/2;
        }
        return false;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        return false;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        return false;
    }

    @Override
    public boolean scrolled(int amount) {
        return false;
    }
}

And here it is running: Thought doest not support iframe If it doesn’t work in an frame, click here.

The code is structured quite a bit differently from when we polled for input.  The most immediate thing to be aware of is our class declaration:

public class InputDemo implements ApplicationListener, InputProcessor {

We are implementing another interface, InputProcessor, which as you can see adds a number of overrides to our code.  The most important ones we are dealing with here are keyDown and touchDown.  Touch you say?  Yeah, LibGDX treats the mouse and touch input as the same thing.  We will look at this in a bit more detail later on.  In addition to implementing the various methods of our interface, we also need to register our InputProcessor with the global input instance, this is done here:

Gdx.input.setInputProcessor(this);

At this point, our various event handlers will now be called whenever an event occurs.  keyDown will be fired when a key is pressed ( while keyUp is fired when it is released, and keyTyped is fired after it has been fired and released ).  The parameter is the value of the key pressed.  Once again, these values are available in the Keys object.  One thing you may have noticed is that we still poll to see if the Control key is pressed.  The alternative would be to set a flag when the control key is pressed and clear it when it is released.  It is important to realize that a keyDown event will be fired for each individual key fired, so if you want to handle multiple simutanious key presses, this may not be the best way to approach the subject.  Another thing you might notice is that you have to hit the key multiple times to move.  This is because a key press generates only a single event ( as does it’s release ).  If you want to have the old behavior that holding down the key will move the character continously, you will need to implement the logic yourself.  Once again, this can simply be done by setting a flag in your code on keyDown and toggle it when the keyUp event is called.

The touchDown event on the other hand is much more straight forward.  It can be a bit confusing handling “mouse” events called “touches”, but it makes sense.  Generally the logic you handle for both would be exactly the same, so no sense treating them differently.  The parameters passed in to touchDown are the x and y coordinates of the touch/click location, the pointer and button clicked.  On a mobile device the Button value will always be Buttons.LEFT.  Once again, screen coordinates and image coordinates arent the same, so we need to deal with that in our positioning.  Notice how I glossed over just what exactly pointer is?  Well, pointer is a bit oddly named in my opinion.  TouchIndex would probably have made more sense, especially with pointer having a pair of very well defined meanings already.  The pointer value is value between 0 and n ( defined as 20 in LibGDX, in reality much lower ) that represents the ORDER in which the touch event occurred in the event of multiple simultaneous touches.  Therefore if you have multiple fingers touching, a pointer value of 0 would indicate that this touch event represents the first finger to touch the screen, while a value of 3 would be the fourth finger to touch the screen.  Dont worry, we will talk about this later when we deal specifically with touch.

Previous PartTable Of ContentsNext Part

Scroll to Top