LibGDX Nesting Tables for gameboard grid

2019-09-17 06:10发布

问题:

I am playing with LibGDX and trying to set up a simple board game.

public void show() {
    width       = Gdx.graphics.getWidth();
    height      = Gdx.graphics.getHeight();
    viewport    = new FitViewport(STAGE_WIDTH, STAGE_HEIGHT);
    stage       = new Stage(viewport);
    sceneBoard  = new GridSceneBoard(10, 30, GridBoardCell.Type.CHECKERED);
    rootTable   = new Table();

    rootTable.setFillParent(true);
    sceneBoard.setFillParent(true);

    rootTable.add(sceneBoard);

    stage.addActor(rootTable);
    Gdx.input.setInputProcessor(stage);
}

a GridSceneBoard extends a Table to conveniently make a grid of images like a chess board. The render method is as follows:

public void render(float delta) {
    // Set black background.
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    // Uncomment for table lines during debugging.
    rootTable.debug();
    sceneBoard.debug();
    Table.drawDebug(stage);

    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
}

I want to nest the tables for better UI layout (eventually), but when I run the code I get:

I've read TableLayout's documentation as well as LibGDX's scene2d.ui documentation, what am I doing wrong? I am using LibGDX 1.0.

回答1:

Its very clear the documentation [1] that

Normally a widget's size is set by its parent and setFillParent must not be used. setFillParent is for convenience only when the widget's parent does not set the size of its children (such as the stage).

So, I basically should never have sceneBoard.setFillParent(true). Only the root table should fill its parent.

[1] https://github.com/libgdx/libgdx/wiki/Scene2d.ui#stage-setup