如何使用libGDX和键盘按键移动精灵?

11

我刚开始使用Java和LibGDX,有这段代码,非常简单,它将一个精灵打印到屏幕上。这个代码完美地运行了,我从中学到了很多。

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() {
}
当用户按下键盘上的 D 键时,我应该如何修改 marioX 的值?

4个回答

32

对于你目前的任务,你可能甚至不需要实现InputProcessor。你可以在render()方法中像这样使用Input.isKeyPressed()方法。

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();
}

需要注意的是,我将马里奥的位置坐标设为浮点数,并将移动方式更改为基于时间的移动。marioSpeed是马里奥每秒应该沿任意方向行进的像素数。Gdx.graphics.getDeltaTime()将以秒为单位返回自上次调用render()以来经过的时间。在大多数情况下,强制转换为int实际上并不必要。

另外,我们在http://www.badlogicgames.com/forum上有论坛,您可以在那里提出关于libgdx的特定问题!

希望这能帮到你, Mario


2
在您的游戏循环方法中(可能是渲染或创建一个),需要添加一个输入处理程序(实现InputProcessor)。InputProcessor类有像以下这些方法:
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);

而且类 Input.Keys 有许多静态变量作为键码。

例如:

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

所以,实现关键*方法并检查是否按下某些键并从马里奥的X/Y增加或减少。

编辑: 请查看以下链接: 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

或者,在trunk中,如何处理演示输入: http://code.google.com/p/libgdx/source/browse/#svn%2Ftrunk%2Fdemos

希望能帮到你


dominicbri7为什么使用KeyListener接口?而你使用InputProcessor?它们之间有什么区别吗? - dotty
@dotty KeyListener 是一个 Java(本地)类。而 InputProcessor 则是 GDX 类。根据我的经验,当我使用引擎时,总是会使用引擎的全部功能。 - jotapdiez

2
你可以使用接口 KeyListener 来检测键盘动作。
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
        }
    }

}

keyPressed()应该在渲染方法中吗?因为我想每帧都要检查这个。 - dotty

1

我倾向于使用一个InputController来存储所有标准按键以供检查。

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;
    }
}

然后我所需要做的就是在游戏的create方法中创建KeyboardController。
controller = new KeyboardController();

然后告诉GDX使用它来监听事件。
Gdx.input.setInputProcessor(controller);

最后,如果我想检查某个键是否被按下,可以执行以下操作:

if(controller.left){
    player.x -= 1;
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接