简体   繁体   中英

libGdx: Sprite is not drawn when there is a stage

I'm sure I'm missing something VERY obvious here, but I'm beginner so don't crush me please. My problem is that I have a stage that has a viewport small than the screen. Now I also want to draw a Sprite on the screen directly using Sprite.draw(SpriteBatch). The position of the Sprite and the stage don't overlap. The stage is drawn just fine, but the Sprite is not visible. When I comment out the stage.draw() part in the render-method, then the Sprite is visible.

Code: This is my render-method:

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0.851f, 0.894f, 0.992f, 1f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.update();

    stage.act(delta);

    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    stage.draw();
    logoSprite.draw(batch);
    batch.end();
}

Here, I initialize the camera and stage (stageHeight is an int that is just 3/5*the height of the screen):

camera = new OrthographicCamera();
    camera.setToOrtho(false, SwapItGame.WIDTH, SwapItGame.HEIGHT);
    stage = new Stage();
    stage.setViewport(1080, stageHeight, true, 0, 0, 1080, stageHeight); //The button part of the menu takes up 3 fifth of the Height of hte screen
    stage.setCamera(camera);

Here I initialize my Sprite (The position value for the sprite is rather complex, just ignore it. It's certainly above the stage):

        logoSprite = skin.getSprite("logo");
        logoSprite.setPosition((SwapItGame.WIDTH-logoSprite.getWidth())/2, (SwapItGame.HEIGHT-stageHeight-logoSprite.getHeight())/2 + stageHeight);

Is is impossible to have a Sprite and a stage on the same Screen? Or am I doing something fundamentally wrong?

Try moving

stage.draw();

above batch operations

stage.draw();
batch.setProjectionMatrix(camera.combined);
batch.begin();
logoSprite.draw(batch);
batch.end();

I know this is old, but in the case that you can't or don't want to move your stage.draw() method, just call batch.end() right before your stage.draw(), then restart your batch immediately...I am using separate game screen states for different things in my game and tried to move my stage.draw() around and it only broke other things within my class so I finally just tried this, which worked like a charm and may help someone if the above solution doesn't work easily.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM