InputProcessor使用情况

时间:2017-10-31 19:45:02

标签: java libgdx

我是游戏开发的新手,我正在尝试用多个屏幕构建简单的2D游戏(mainMenu,playScreen,..)。在PlayScreen中,我正在渲染动画,并想检查是否触摸/点击了该动画。  如何检查是否在该动画中发生了触摸?由于我有多个屏幕,最好分别使用屏幕 InputProcessor (对所有屏幕使用相同的输入处理器)或同一类(每个屏幕使用自己的处理器?我的当前代码如下:

public class InputHandler implements InputProcessor {
private Handler h;
public boolean touch = false;

public InputHandler(Handler h) {
    this.h = h;
}


@Override
public boolean keyDown(int keycode) {
    return false;
}

@Override
public boolean keyUp(int keycode) {
    return false;
}

@Override
public boolean keyTyped(char character) {
    return false;
}

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    touch = true;
    return false;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    touch = false;
    return false;
}

PlayScreen类:

public class PlayScreen implements Screen {
private SpriteBatch batch;
Animation monster;
Texture background;
public TextureAtlas atlas;
TextureRegion region;
float stateTime;
private int height;
private Viewport viewport;
private Camera camera;
private int width;
private float elapsedTime = 0;
ShapeRenderer shapeRenderer;
private Handler h;
private Stage stage;
private InputProcessor processor;

public PlayScreen(Handler h){
    this.h = h;
    batch = h.batch;
    camera = h.camera;
    viewport = h.viewport;
    height = h.height;
    width = h.width;
    stage = new Stage(viewport,batch);
    stateTime = 0f;
    background = new Texture("hd/hd_background.png");
    atlas = new TextureAtlas(Gdx.files.internal("mons1.txt"));
    monster = new Animation(1/15f, atlas.getRegions());

}



@Override
public void show() {
input.setInputProcessor(processor);
}

@Override
public void render(float delta) {

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();

    batch.draw(background ,0,0,width, height);
    elapsedTime += Gdx.graphics.getDeltaTime();

    region = (TextureRegion) monster.getKeyFrame(elapsedTime, true);
    batch.draw(region, width/2-region.getRegionWidth()/2,height - region.getRegionHeight() -30);
}

@Override
public void resize(int width, int height) {
    h.viewport.update(width, height);
    camera.update();
    h.viewport.apply();

}

@Override
public void dispose() {
    background.dispose();
    atlas.dispose();
    batch.dispose();
}

我也使用单独的类Handler,我从中获取所有游戏数据(我也不确定这是否是最好的决定)。

1 个答案:

答案 0 :(得分:1)

使用InputProcessor的最佳方法是在每个Screen中实施这些方法。

public class PlayScreen implements Screen, InputProcessor {}

现在你有一个ScreenInputProcessor的课程。点击事件的相关方法是touchDown方法。

使用screenXscreenY值,您可以使用一些基本数学来确定点击是否在您的动画中。

祝你好运!如果您还有其他问题,请随时在下面发表评论!