【问题标题】:How can add a drawing function to a button in libgdx?如何将绘图功能添加到 libgdx 中的按钮?
【发布时间】:2015-08-13 19:10:09
【问题描述】:

我正在使用 Screen-2D 构建一个按钮。我想在单击时为按钮提供一个功能,将绘制一个精灵我该怎么做。这不是我所有的代码,但足以说明我在说什么。

public void create () {
    buttonStyle = new TextButtonStyle();
    buttonStyle.up = skin.getDrawable("button");
    buttonStyle.over = skin.getDrawable("buttonpressed");
    buttonStyle.down = skin.getDrawable("buttonpressed");
    buttonStyle.font = font;
    button = new TextButton("START", buttonStyle);

    stage.addActor(button);
    Gdx.input.setInputProcessor(stage);
    button.addListener(new InputListener() {    
        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            drawTile(200,50);
            return true;
        }
    });
}

// method used to draw a sprite when passing certain coordinates 
public void drawTile(int x , int y) {    
    spriteBatch.draw(sprite, x  , y   );
}

public void render () {
    Gdx.gl.glClearColor(1f, 0f, 0f, 1f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.update();
    spriteBatch.begin();
    spriteBatch.draw(background, 0, 0);
    drawGrid();
    spriteBatch.draw(startButton, 0, 0);
    stage.draw();
    spriteBatch.end()
}

【问题讨论】:

    标签: java libgdx 2d game-engine


    【解决方案1】:

    你的想法是对的。看这个例子:

    button.addListener(new ChangeListener() {
        @Override
        public void changed (ChangeEvent event, Actor actor) {
            drawTile(200,50);
        }
    }); 
    

    https://github.com/libgdx/libgdx/wiki/Scene2d.ui#changeevents

    【讨论】:

      【解决方案2】:

      我认为您需要阅读更多有关 LibGDX 和 Scene2D 工作原理的教程:事件处理在您的渲染方法之前完成,因此当您清除屏幕时任何绘图都将被擦除。

      正确的方法是在单击触发时将精灵(作为可绘制对象)添加到小部件组。然后舞台渲染将渲染您的所有组件,包括您的精灵。

      与 MVC 模式相比:舞台是你的模型,当事件发生时你修改你的模型,渲染方法是你的模型的视图(绘制你的模型)。

      【讨论】:

        猜你喜欢
        • 2022-11-01
        • 2012-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-31
        • 2014-08-29
        相关资源
        最近更新 更多