需要帮助的使用libgdx scene2d按钮 [英] Need help in using scene2d button in libgdx

查看:149
本文介绍了需要帮助的使用libgdx scene2d按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来libGDX。我试图通过扩大com.badlogic.gdx.scenes.scene2d.ui.Button创建一个自定义按钮。

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

我能在屏幕上看到我的按钮。现在我想做的事就是添加一些code被点击或触摸按钮时,它被调用。是否有人可以帮助?

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 ?

推荐答案

它不工作,因为你需要的setBounds你的按钮。如果你想绘制按钮的位置(175,100),你可以只直接从按钮类和呼叫

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,宽度,高度);

然后添加监听器会工作,因为现在你的按钮实际上有一个位置,并在舞台的区域。如果您仍然需要扩展按钮类你自己的原因,你可以设置ditectly在扩展类的范围,也可以通过在你的类RestartButton另一种说法。类似的:

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

然后,按键会自动绘制,而不需要压倒一切的绘制方法你想要的位置。通过添加监听器 this.addListener(yourListener);

希望它帮助。

这篇关于需要帮助的使用libgdx scene2d按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆