A
A
Alexander Vasilenko2015-08-23 10:00:51
Java
Alexander Vasilenko, 2015-08-23 10:00:51

How to make the keyboard work in a game written with libgdx?

Hello, friends.
Yesterday I decided to master libgdx, because I really want to pee games in my free time, in short, have some fun. But my mood was spoiled by a terrible thing.
I decided to start small and went through this lesson. The code of the whole program is at the very bottom of the page from this link.
Notice the render() method and these lines:

// обработка пользовательского ввода
        //обработка ввода мыши
        if(Gdx.input.isTouched()) {
            Vector3 touchPos = new Vector3();
            touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
            camera.unproject(touchPos);
            bucket.x = touchPos.x - 64 / 2;
        }
        //обработка ввода с клавиатуры
        if(Gdx.input.isKeyPressed(Keys.LEFT)) bucket.x -= 200 * Gdx.graphics.getDeltaTime();
        if(Gdx.input.isKeyPressed(Keys.RIGHT)) bucket.x += 200 * Gdx.graphics.getDeltaTime();

The problem is with the last two lines from this piece of code. The bottom line is that the program does not respond at all to any keystroke.
Are there any ideas? Maybe someone faced a problem?
OS: Mac OS X Yosemite;
IDE: IntelliJ IDEA

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
iundersun, 2015-08-23
@SanchelliosProg

I used to work with InputProcessorom
it has suitable methods for handling both mouse/keyboard and touchscreen
here is an example:

public class GameScreen implements Screen, InputProcessor{

  //вызывается при создании нового экрана (Screen)
  public void show(){	
      //говорим что будем отбрабатывать нажатия тут
      Gdx.input.setInputProcessor(this); 
  }
  
  //работаем с клавиатурой
  public boolean keyDown(int key){
      if(key==Keys.LEFT)) bucket.x -= 200 * Gdx.graphics.getDeltaTime();
      if(key==Keys.RIGHT)) bucket.x += 200 * Gdx.graphics.getDeltaTime();
  }
  
  //работаем с мышей/тачскрином
  public boolean touchDown(int screenX, int screenY, int pointer, int button){
      Vector3 touchPos = new Vector3(screenX, screenY);
            camera.unproject(touchPos);
            bucket.x = touchPos.x - 64 / 2;
  }
  
  public void render(float delta)
  {
    Gdx.gl.glClearColor(1.0F, 0.0F, 0.0F, 1.0F);
    Gdx.gl.glClear(16384);
    
    //рисуем что-то
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question