AndroidStudio libgdx ChangeListener not working

老子叫甜甜 提交于 2019-12-12 03:27:33

问题


Android Studio-libgdx making a 2d game. I have a Main which creates the MenuState, in the render method I made this

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

    camera.update();
    myGame.batch.setProjectionMatrix(camera.combined);
    batch = new SpriteBatch();
    skin = new Skin(Gdx.files.internal("data/uiskin.json"));
    stage = new Stage();

    final TextButton button = new TextButton("Click me", skin, "default");

    button.setWidth(400f);
    button.setHeight(100f);
    button.setPosition(Gdx.graphics.getWidth() / 2 - 100f, Gdx.graphics.getHeight() / 2 - 10f);

    button.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            Gdx.gl.glClearColor(1, 0, 0, 1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        }
    });
    stage.addActor(button);

    Gdx.input.setInputProcessor(stage);

    myGame.batch.begin();
    stage.draw();
    myGame.batch.end();
}

I checked some tutorials on how to make a menu and that's pretty much what I'm testing in here. But when I run the app the button appears and nothing happens if I click it. I've tried testing with the ClickListener but still doesn't work. Any ideas? Or am I doing it wrong or it should be in another method? I'm new with libgdx. Thanks in advance.


回答1:


You are creating new instances of the stage, skin and batch in render method? Move them away from your render method ;)

Render should look more like this:

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

        camera.update();
        myGame.batch.setProjectionMatrix(camera.combined);

        myGame.batch.begin();
        stage.draw();
        myGame.batch.end();
}

And in constructor:

    batch = new SpriteBatch();
    skin = new Skin(Gdx.files.internal("data/uiskin.json"));
    stage = new Stage();

    final TextButton button = new TextButton("Click me", skin, "default");

    button.setWidth(400f);
    button.setHeight(100f);
    button.setPosition(Gdx.graphics.getWidth() / 2 - 100f, Gdx.graphics.getHeight() / 2 - 10f);

    button.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            Gdx.gl.glClearColor(1, 0, 0, 1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        }
    });
    stage.addActor(button);

    Gdx.input.setInputProcessor(stage);


来源:https://stackoverflow.com/questions/36819541/androidstudio-libgdx-changelistener-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!