我是新手,我想制作像马里奥这样的游戏,我遇到关键按键的问题。这是我的代码。
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 :(得分: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;
}
}