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

dot*_*tty 10 java sprite libgdx

我刚刚开始使用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() {
}
Run Code Online (Sandbox Code Playgroud)

}

marioX当用户按下D键盘时,如何修改该值?

bad*_*gic 31

对于您手头的任务,您甚至可能不需要实现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();
}
Run Code Online (Sandbox Code Playgroud)

另请注意,我制作了马里奥花车的位置坐标,并将运动改为基于时间的运动.marioSpeed是马里奥每秒在任何方向上行进的像素数.Gdx.graphics.getDeltaTime()返回自上次调用render()以来经过的时间(以秒为单位).在大多数情况下,实际上不需要转换为int.

顺便说一句,我们在http://www.badlogicgames.com/forum上有论坛,你也可以在这里询问libgdx的具体问题!

马里奥