Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a sprite with the keyboard keys using libGDX?

i have just started using java and libgdx and have this code, very simply it prints a sprite onto the screen. This works perfectly, and i learnt a lot from it.

package com.MarioGame;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
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;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.InputProcessor;

public class Game implements ApplicationListener {
private SpriteBatch batch;
private Texture marioTexture;
private Sprite mario;
private int marioX;
private int marioY;

@Override
public void create() {
    batch = new SpriteBatch();
    FileHandle marioFileHandle = Gdx.files.internal("mario.png"); 
    marioTexture = new Texture(marioFileHandle);
    mario = new Sprite(marioTexture, 0, 158, 32, 64);
    marioX = 0;
    marioY = 0;
}

@Override
public void render() {
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    batch.begin();
    batch.draw(mario, marioX, marioY);
    batch.end();
}


@Override
public void resume() {
}

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

@Override
public void pause() {
}

@Override
public void dispose() {
}

}

How would I modify the marioX value when a user presses D on their keyboard?

like image 207
dotty Avatar asked Apr 29 '11 14:04

dotty


4 Answers

For your task at hand you might not even need to implement InputProcessor. You can use the Input.isKeyPressed() method in your render() method like this.

float marioSpeed = 10.0f; // 10 pixels per second.
float marioX;
float marioY;

public void render() {
   if(Gdx.input.isKeyPressed(Keys.DPAD_LEFT)) 
      marioX -= Gdx.graphics.getDeltaTime() * marioSpeed;
   if(Gdx.input.isKeyPressed(Keys.DPAD_RIGHT)) 
      marioX += Gdx.graphics.getDeltaTime() * marioSpeed;
   if(Gdx.input.isKeyPressed(Keys.DPAD_UP)) 
      marioY += Gdx.graphics.getDeltaTime() * marioSpeed;
   if(Gdx.input.isKeyPressed(Keys.DPAD_DOWN)) 
      marioY -= Gdx.graphics.getDeltaTime() * marioSpeed;

   Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
   batch.begin();
   batch.draw(mario, (int)marioX, (int)marioY);
   batch.end();
}

Also note that i made the position coordinates of mario floats and changed the movement to time-based movement. marioSpeed is the number of pixels mario should travel in any direction per second. Gdx.graphics.getDeltaTime() returns you the time passed since the last call to render() in seconds. The cast to int is actually not necessary in most situations.

Btw, we have forums at http://www.badlogicgames.com/forum where you ask libgdx specific questions as well!

hth, Mario

like image 194
badlogic Avatar answered Nov 11 '22 02:11

badlogic


You can use the interface KeyListener to detect keyboard action.

public class Game implements ApplicationListener, KeyListener {

@Override
public void create() {
    //Important
    this.addKeyListener(this);

    // TODO Auto-generated method stub
    batch = new SpriteBatch();

    FileHandle marioFileHandle = Gdx.files.internal("mario.png"); 
    marioTexture = new Texture(marioFileHandle);
    mario = new Sprite(marioTexture, 0, 158, 32, 64);

    marioX = 0;
    marioY = 0;


}

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == 68) { //it's the 'D' key
            //Move your mario
        }
    }

}
like image 39
dominicbri7 Avatar answered Nov 11 '22 02:11

dominicbri7


In your game loop method (maybe render or make one) need to add an input handler (implementing InputProcessor). The class InputProcessor have methods like:

public boolean keyDown (int keycode);

/**
 * Called when a key was released
 * 
 * @param keycode one of the constants in {@link Input.Keys}
 * @return whether the input was processed
 */
public boolean keyUp (int keycode);

/**
 * Called when a key was typed
 * 
 * @param character The character
 * @return whether the input was processed
 */
public boolean keyTyped (char character);

and the class Input.Keys has a lot of static varibles as keycodes. For example:

        public static final int D = 32;
        public static final int A = 29;
        public static final int S = 47;
        public static final int W = 51;

So, implement key* methods and check if some key are pressed and increment or decrement X/Y from mario.

EDIT: Check this links: http://code.google.com/p/libgdx/source/browse/trunk/gdx/src/com/badlogic/gdx/InputProcessor.java http://code.google.com/p/libgdx/source/browse/trunk/gdx/src/com/badlogic/gdx/Input.java

or, in trunk, how to a demos handle input: http://code.google.com/p/libgdx/source/browse/#svn%2Ftrunk%2Fdemos

Hope help

like image 2
jotapdiez Avatar answered Nov 11 '22 04:11

jotapdiez


My preferred method is to use an InputController which stores all the standard keys ready for checking.

import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.math.Vector2;

public class KeyboardController  implements InputProcessor {
    public boolean left,right,up,down;
    public boolean isMouse1Down, isMouse2Down,isMouse3Down;
    public boolean isDragged;
    public Vector2 mouseLocation = new Vector2(0,0);

    @Override
    public boolean keyDown(int keycode) {
        boolean keyProcessed = false;
        switch (keycode) // switch code base on the variable keycode
        {
            case Keys.LEFT:     // if keycode is the same as Keys.LEFT a.k.a 21
                left = true;    // do this
                keyProcessed = true;    // we have reacted to a keypress 
                break;
            case Keys.RIGHT:    // if keycode is the same as Keys.LEFT a.k.a 22
                right = true;   // do this
                keyProcessed = true;    // we have reacted to a keypress 
                break;
            case Keys.UP:       // if keycode is the same as Keys.LEFT a.k.a 19
                up = true;      // do this
                keyProcessed = true;    // we have reacted to a keypress 
                break;
            case Keys.DOWN:     // if keycode is the same as Keys.LEFT a.k.a 20
                down = true;    // do this
                keyProcessed = true;    // we have reacted to a keypress
        }
        return keyProcessed;    //  return our peyProcessed flag
    }
    @Override
    public boolean keyUp(int keycode) {
        boolean keyProcessed = false;
        switch (keycode) // switch code base on the variable keycode
        {
            case Keys.LEFT:     // if keycode is the same as Keys.LEFT a.k.a 21
                left = false;   // do this
                keyProcessed = true;    // we have reacted to a keypress 
                break;
            case Keys.RIGHT:    // if keycode is the same as Keys.LEFT a.k.a 22
                right = false;  // do this
                keyProcessed = true;    // we have reacted to a keypress 
                break;
            case Keys.UP:       // if keycode is the same as Keys.LEFT a.k.a 19
                up = false;     // do this
                keyProcessed = true;    // we have reacted to a keypress 
                break;
            case Keys.DOWN:     // if keycode is the same as Keys.LEFT a.k.a 20
                down = false;   // do this
                keyProcessed = true;    // we have reacted to a keypress
        }
        return keyProcessed;    //  return our peyProcessed flag
    }
    @Override
    public boolean keyTyped(char character) {
        return false;
    }
    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        if(button == 0){
            isMouse1Down = true;
        }else if(button == 1){
            isMouse2Down = true;
        }else if(button == 2){
            isMouse3Down = true;
        }
        mouseLocation.x = screenX;
        mouseLocation.y = screenY;
        return false;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        isDragged = false;
        //System.out.println(button);
        if(button == 0){
            isMouse1Down = false;
        }else if(button == 1){
            isMouse2Down = false;
        }else if(button == 2){
            isMouse3Down = false;
        }
        mouseLocation.x = screenX;
        mouseLocation.y = screenY;
        return false;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        isDragged = true;
        mouseLocation.x = screenX;
        mouseLocation.y = screenY;
        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        mouseLocation.x = screenX;
        mouseLocation.y = screenY;
        return false;
    }
    @Override
    public boolean scrolled(int amount) {
        return false;
    }
}

Then all I need to do is make the KeyboardController in the create method of your game with

controller = new KeyboardController();

Then tell GDX to use it to listen for events

Gdx.input.setInputProcessor(controller);

Finally if I want to check if a key is pressed I can go

if(controller.left){
    player.x -= 1;
} 
like image 1
dfour Avatar answered Nov 11 '22 04:11

dfour