Need help in using scene2d button in libgdx

♀尐吖头ヾ 提交于 2020-01-15 07:11:12

问题


I am new to libGDX. I am trying to create a custom button by extending com.badlogic.gdx.scenes.scene2d.ui.Button.

I want all the button related logic in this class. But I am not getting how to make the click work. I read many tutorials regarding adding Event Listeners but nothing is working.

public class RestartButton extends Button {

public RestartButton(ButtonStyle style) {
    super(style);

}

@Override
public void draw(SpriteBatch batch, float parentAlpha) {
    batch.draw(TextureProvider.getInstance().getRestart(), 175, 100);
}

}

And i am trying to add my button in the screen(i.e in show method) like this

RestartButton restartButton;
restartButton=new RestartButton(new ButtonStyle());
Stage stage;
stage.addActor(restartButton);

I am able to see my button on the screen. Now what i want to do is add some code which gets invoked when button is clicked or touched. Can someone please help ?


回答1:


It does not work because you need to setBounds for your Button. If you wanted to draw the button in the position (175, 100) you could just create a Button directly from Button Class and call

button.setBounds(x, y, width, height);

Then adding the listener will work because now your button will actually have a position and an area in the stage. If you still need to extend the button class for your own reasons, you can set the bounds in the extended class ditectly or you can pass another argument in your RestartButton class. Similar to:

   public RestartButton(ButtonStyle style, Vector2 position, Vector2 size) {
       super(style);
       this.setBounds(position.x, position.y, size.x, size.y);
   }

Then the button will automatically be drawn to the position you want without the need of overriding draw method. add the listener by using this.addListener(yourListener);

Hope it helps.




回答2:


restartButton = new RestartButton(new ButtonStyle());
button.addListener(new ClickListener() {
    @Override
    public void clicked(InputEvent event, float x, float y) {
        System.out.println("Restart clicked!");
    }
});
stage.addActor(restartButton);


来源:https://stackoverflow.com/questions/24327860/need-help-in-using-scene2d-button-in-libgdx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!