簡體   English   中英

libgdx inputListener不適用於actor

[英]libgdx inputListener doesn't work with actor

我嘗試將InputListener與Actor一起使用,但不起作用。 我真的不知道為什么 我發現了很多有關此的信息,並看到了官方文檔,但沒有一個沒有幫助我。

觸摸精靈時,不會顯示我的日志消息。 但是,如果我使用全局輸入處理器(用於整個屏幕),則可以正常工作,但是我只想為演員添加一個偵聽器。

我究竟做錯了什么?

public class GameScreen implements Screen {
    final Launch launch;
    Texture texture;
    Stage stage;


    public GameScreen(Launch launch) {
        Gdx.app.setLogLevel(Application.LOG_DEBUG);
        this.launch = launch;
        texture = new Texture("hero.png");
        stage = new Stage();
        Hero hero = new Hero();
        hero.addListener(new HeroListener());
        stage.addActor(hero);
        Gdx.input.setInputProcessor(stage);

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0.2f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        stage.draw();
        stage.act(Gdx.graphics.getDeltaTime());

    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void show() {
    }

    @Override
    public void hide() {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }

    @Override
    public void dispose() {
        stage.dispose();
        texture.dispose();
    }

    private class Hero extends Actor {

        @Override
        public boolean addListener(EventListener listener) {
            Gdx.app.debug("MyTag", "my debug message");
            return super.addListener(listener);
        }

        @Override
        public void draw(Batch batch, float parentAlpha) {
            batch.draw(texture, 0, 0, 500, 500);
        }
    }

    private class HeroListener extends InputListener {
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            Gdx.app.debug("MyTag", "touch down");
            return super.touchDown(event, x, y, pointer, button);
        }

        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            Gdx.app.debug("MyTag", "touch up");
            super.touchUp(event, x, y, pointer, button);
        }
    }
}

問題是您沒有給演員任何尺寸或位置。 InputListener事件工作whitin的的邊界Actor 如果您沒有為Actor定義任何大小,它將永遠不會收到事件。

Hero hero = new Hero();
hero.addListener(new HeroListener());

hero.setBounds(0, 0, 500, 500);

stage.addActor(hero);

那應該使您的InputListener在(0,0),(500,500)范圍內監聽touchDown / Up事件。

另外,這很方便,因為您可以在以下繪制時使用這些邊界:

@Override
public void draw(Batch batch, float parentAlpha) {
    batch.draw(texture, getX(), getY(), getWidth(), getHeight());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM