StudioThug
StudioThug

Reputation: 11

How can add a drawing function to a button in libgdx?

I am using Screen-2D to build a button. I want give the button a function when it is click a sprite will be drawn how can i do this. This isn't all all my code but enough to show what am talking about.

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()
}

Upvotes: 0

Views: 843

Answers (2)

mgsx-dev
mgsx-dev

Reputation: 440

I think you need to read more tutorials about how LibGDX and Scene2D works : Event processing is done before your render method, so any drawing will be erased when you clear screen.

A right approach would be to add a sprite (as Drawable) to a widget group when click firing. Then stage rendering will renderer all your component including your sprites.

Comparaing to MVC pattern : The stage is your model, you modifiy your model when events occurs and the render method is the view of your model (draw your model).

Upvotes: 0

tobloef
tobloef

Reputation: 1891

You got the right idea. See this example:

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

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

Upvotes: 1

Related Questions