Как переместить спрайт с помощью клавиш клавиатуры с помощью 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() {
}
}
Как изменить значение marioX
, когда пользователь нажимает D
на клавиатуре?
Ответы
Ответ 1
Для вашей задачи вам может даже не понадобиться реализовать InputProcessor. Вы можете использовать метод Input.isKeyPressed() в методе render(), подобный этому.
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 фактически не является необходимым в большинстве ситуаций.
Btw, у нас есть форумы на http://www.badlogicgames.com/forum, где вы также задаете конкретные вопросы по libgdx!
НТН,
Марио
Ответ 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 от mario.
EDIT:
Проверьте ссылки:
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, как входной диск demos:
http://code.google.com/p/libgdx/source/browse/#svn%2Ftrunk%2Fdemos
Помощь надежда
Ответ 3
Вы можете использовать интерфейс 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 the 'D' key
//Move your mario
}
}
}
Ответ 4
Мой предпочтительный метод - использовать 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;
}
}
Тогда все, что мне нужно сделать, это сделать KeyboardController в методе создания вашей игры с помощью
controller = new KeyboardController();
Затем скажите GDX использовать его для прослушивания событий
Gdx.input.setInputProcessor(controller);
Наконец, если я хочу проверить, нажата ли клавиша, я могу пойти
if(controller.left){
player.x -= 1;
}