【问题标题】:Precise position of widgets for libGDX scene2dlibGDX scene2d 的小部件的精确位置
【发布时间】:2017-05-26 21:42:19
【问题描述】:

我想在我的 libGDX 应用程序中设置一个可按下的钢琴键,如下所示:

当一个键被按下时,我需要将它从上到下更改(这很容易使用图像按钮)。

我正在苦苦挣扎的是如何布局所有按钮,以便它们用于类似于钢琴键盘的东西。白色钢琴键图像是矩形的,但黑色钢琴键需要放在它上面。下面显示了我的一个白色钢琴键图像的样子,顶角有一个死角,我打算放一个黑色音符。

使用Table 是行不通的,因为表格会并排布置所有内容,这会给我留下空白。我看到你可以使用Stack,但这只是将每个孩子直接放在最后一个孩子的上面,所以这似乎也没有帮助。

如果有帮助,我的代码是这样的:

Skin skin;
Stage stage;
SpriteBatch batch;
private TextButton button1;
private TextButton button2;

@Override
public void create () {
    batch = new SpriteBatch();
    stage = new Stage();
    Gdx.input.setInputProcessor(stage);

    createSkin();

    Table table = new Table();
    table.setFillParent(true);
    stage.addActor(table);

    // Create a button with the "default" TextButtonStyle. A 3rd parameter can be used to specify a name other than "default".
    button1 = new TextButton("First note", skin);
    button1.getLabel().setFontScale(5);

    button2 = new TextButton("Second note", skin);
    button2.getLabel().setFontScale(5);

    table.add(button1).width(500).height(500);
    table.add(button2).width(500).height(200);
}

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

@Override
public void resize (int width, int height) {
    stage.getViewport().update(width, height, true);
}

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

private void createSkin() {
    skin = new Skin();

    Pixmap pixmap = new Pixmap(1, 1, Pixmap.Format.RGBA8888);
    pixmap.setColor(Color.WHITE);
    pixmap.fill();
    skin.add("white", new Texture(pixmap));

    skin.add("default", new BitmapFont());

    TextButton.TextButtonStyle textButtonStyle = new TextButton.TextButtonStyle();
    textButtonStyle.up = skin.newDrawable("white", Color.DARK_GRAY);
    textButtonStyle.down = skin.newDrawable("white", Color.BLUE);
    textButtonStyle.checked = skin.newDrawable("white", Color.DARK_GRAY);
    textButtonStyle.over = skin.newDrawable("white", Color.DARK_GRAY);
    textButtonStyle.font = skin.getFont("default");
    skin.add("default", textButtonStyle);
}

这会呈现:

据我所知,使用表格无法重叠,但我找不到另一种方法。使用scene2d可以做到这一点吗?

【问题讨论】:

    标签: android libgdx 2d-games scene2d


    【解决方案1】:

    直接将所有代表键的按钮添加到舞台,而不将它们放在表格中。手动设置它们的位置。应该很容易手动完成,因为钢琴键有清晰的图案。添加白键后添加黑键。这样您就不必担心白键是非矩形的,因为黑键将优先接收输入。

    【讨论】:

      【解决方案2】:

      最简单的解决方案似乎是创建具有相同视口的第二个 Stage(在调整大小的情况下,阶段需要以相同的方式表现)并将其放置在您当前的之上。您需要创建相同的表格,但只用黑色音符填充它(您当前的阶段当然只包含白色音符)。

      请注意,您需要使用 InputMultiplexer 来获取两个阶段的事件 - 您可以 read here 了解如何使用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-02
        • 1970-01-01
        • 1970-01-01
        • 2014-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多