2016-01-23 60 views
0

我是新手,我想制作像马里奥一样的游戏,并且我有关于按键的问题。这是我的代码。Libgdx如何获得按键事件?

public class MyGdxGame extends ApplicationAdapter implements InputProcessor{ 

private TextureAtlas myTexture; 
private SpriteBatch sprite; 
private TextureRegion solider; 
private Vector2 position=new Vector2(0,0); 

    @Override 
    public void create() { 
     sprite= new SpriteBatch(); 
     myTexture=new TextureAtlas("metal-slug.txt"); 
     solider=myTexture.findRegion("solider-run"); 
     Gdx.input.setInputProcessor(this);   
} 
    @Override 
    public void render() { 
     Gdx.gl.glClearColor(1, 0, 0, 1); 
     Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); 
     sprite.begin(); 
     sprite.draw(solider, position.x, 0);        
     sprite.end(); 
} 
    @Override 
    public boolean keyDown(int keycode) {   
     if (keycode== Keys.D){ 
      position.x+=10; 
     } 
     if (keycode== Keys.A){ 
      position.x-=10; 
     } 
     return false; 
    } 

    } 

问题是对象只是当我按下键,但是当键释放它停下来,我要当按住键,对象应该移动到屏幕右侧移动。

回答

0

您可以通过使用变量移动来移动对象。

public class MyGdxGame extends ApplicationAdapter implements InputProcessor  { 


    private TextureAtlas myTexture; 
    private SpriteBatch sprite; 
    private TextureRegion solider; 
    private Vector2 position=new Vector2(0,0); 
    private float move=0f; 

@Override 
public void create() { 
    sprite= new SpriteBatch(); 
    myTexture=new TextureAtlas("metal-slug.txt"); 
    solider=myTexture.findRegion("solider-run"); 
    Gdx.input.setInputProcessor(this);   
} 
@Override 
public void render() { 
    Gdx.gl.glClearColor(1, 0, 0, 1); 
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); 
    sprite.begin(); 
    sprite.draw(solider, position.x+move, 0);       
    sprite.end(); 
} 
@Override 
public boolean keyDown(int keycode) {   
    if (keycode== Keys.D){ 
     move=1; 
    } 
    if (keycode== Keys.A){ 
     move=-1; 
    } 
    return false; 
} 

}