0

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()
}
tobloef
1,8913 gold badges23 silver badges40 bronze badges
asked Aug 13, 2015 at 19:10

2 Answers 2

1

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

answered Aug 14, 2015 at 8:29
Sign up to request clarification or add additional context in comments.

Comments

0

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).

answered Aug 14, 2015 at 19:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.