LibGDX:Buttonis在舞台上被绘制两次

时间:2018-05-03 09:44:38

标签: java libgdx

所以我的问题是,当游戏结束时,它会将游戏投入一个新的屏幕(称为“EndState”),在那里我绘制了标题“Game Over”和一个名为“Restart”的ImageButton,因此背景和播放器以及所有内容else与之前的屏幕相同,但已冻结。当我单击我的重启按钮时,它会向下移动10px(按效果,使用pressedOffsetY实现),但是我看到相同的按钮后面,我找到解决这个问题的唯一方法是在绘制舞台之前在屏幕上绘制一些东西使用此按钮,但这样我丢失了我的播放器图像以及上一屏幕中的所有其他内容。

我使用Stage绘制ImageButton(因为它是可点击的)这样:

public class EndState implements Screen {
    private Game endGame;
    private Texture gameOver, restartBtnTexture; // textures of title and button
    private SpriteBatch batch;
    private ImageButton restartImgButton; // ImageButton
    private Drawable drawable; //drawable, to store the image and then use it in Style
    private Stage stage; //the stage which will contain button
    private ImageButton.ImageButtonStyle style; // Style

    public EndState(final Game game) {
        this.endGame = game; //I receive game state from the previous state
        gameOver = new Texture(Gdx.files.internal("GameOver.png"));
        restartBtnTexture = new Texture(Gdx.files.internal("Buttons/Button_1.png"));

        drawable = new TextureRegionDrawable(new TextureRegion(restartBtnTexture));
        batch = new SpriteBatch();

        style = new ImageButton.ImageButtonStyle(); // creating style
        style.imageUp = drawable; 9
        style.pressedOffsetY = -10; // when I press the button I move 10px below

        restartImgButton = new ImageButton(style); // creating the button and assigning the Style
        restartImgButton.getImage().setFillParent(true);
        restartImgButton.setBounds(Gdx.graphics.getWidth() / 2 - (Gdx.graphics.getWidth() / 4), Gdx.graphics.getHeight() * 4/8, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 7); // size and position
        restartImgButton.getImageCell().expand().fill();

        stage = new Stage(); // creating stage
        stage.addActor(restartImgButton); //adding button to the stage
        restartImgButton.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                endGame.setScreen(new PlayState(endGame));
            }
        });
        Gdx.input.setInputProcessor(stage);


    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        batch.begin();
        batch.draw(gameOver, Gdx.graphics.getWidth() / 2 - (Gdx.graphics.getWidth() * 2/6), Gdx.graphics.getHeight() * 6/8, Gdx.graphics.getWidth() * 2/3, Gdx.graphics.getWidth() / 3); // drawing Game Over
        batch.end();
        stage.draw(); // drawing restart Button
    }

1 个答案:

答案 0 :(得分:1)

我认为基本问题是你没有在每次渲染时清除屏幕(故意这样,但它也会导致你的问题)。

由于您没有清除屏幕,因此您的最后一个屏幕仍然可见,但此屏幕上绘制的所有内容也是如此(测试按钮移动的次数比您现有的更多,您将开始在任何地方看到它的副本移动它。)

简单的解决方案:不要让任何内容在此屏幕上移动

正确的解决方案,因为您希望旧图形保持不变,不要创建新屏幕,只需在上一个屏幕中插入按钮actor并从那里开始工作