[英]Why isn't my clicklistener working?
这是我的代码
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.viewport.FitViewport;
public class MainMenuScreen extends SpaceInvaderScreen {
SpriteBatch batch;
TextureRegion background;
Stage stage;
TextButton playbutton;
float time = 0;
public MainMenuScreen(Game game){
super(game);
}
@Override
public void show(){
batch = new SpriteBatch();
batch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
background = new TextureRegion(new Texture("data/cool.jpg"), 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
stage = new Stage(new FitViewport(1280, 1080));
Skin uiskin = new Skin(Gdx.files.internal("data/skin/uiskin.json"));
playbutton = new TextButton("Play", uiskin);
playbutton.setWidth(200);
playbutton.setHeight(100);
playbutton.setPosition(980, 620);
playbutton.setBounds(playbutton.getX(), playbutton.getY(), playbutton.getWidth(), playbutton.getHeight());
playbutton.addListener( new ClickListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
game.setScreen( new GameScreen(game));
return true;
};
});
stage.addActor(playbutton);
Gdx.input.setInputProcessor(stage);
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0.15f, 0.15f, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(background, 0, 0);
batch.end();
stage.act();
stage.draw();
time += delta;
}
@Override
public void hide(){
batch.dispose();
background.getTexture().dispose();
}
}
我不确定clicklistener为何无法正常工作。 我也尝试使用touchDown方法,但是它也不起作用。 抱歉,这听起来像是一个愚蠢的问题,对我的图书馆来说还算是新事物
只需尝试以下两件事:我可以看到您正在show方法中构建按钮。 为什么? 在显示任何内容之前 ,拥有一种设置方法并构建该应用程序/游戏/该设置方法中的任何内容的整个布局会更加有意义。 但这只是黑暗中的一枪,我不知道您使用的是这个框架,我可能会犯错。
当您保留同一游戏的多个实例时,另一件事可能会引起问题! 注意仅一次构建游戏,然后传递该单个实例。 为什么这么重要? 因为在game.setScreen( new GameScreen(game));
情况下您可能正在调用game.setScreen( new GameScreen(game));
但是在错误的情况下!
请同时发布您的SpaceInvaderScreen
,以便于调试。
而且,无论如何,您是否尝试调试touchDown
方法? 真的叫吗?
还有两件事: ClickListener
是一个类。 不是界面。 因此,当您覆盖touchDown
方法时,基本上就绕过了超类中的父代码。
尝试在达阵方法中作为第一行调用:
super.touchDown(event, x, y, pointer, button);
另外, ClickListener文档中还说:
当返回true时,将处理事件(...),这不会影响scene2d内部的事件传播,但会导致Stage事件方法返回true,这将占用事件,因此不会将其传递给舞台下的应用程序。
因此,您应该尝试返回false;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.