如何检测文本上的点击(使用LibGdx)。我只想在用户点击文本时更改字体颜色。所以这就是我到目前为止所做的。
public class MainMenuScreen implements Screen,InputProcessor {
final MainClass game;
String playButton = "PLAY";
private int screenWidth;
private int screenHeight;
public MainMenuScreen(final MainClass gam){
game=gam;
Gdx.input.setInputProcessor(this);
screenHeight = Gdx.graphics.getHeight();
screenWidth = Gdx.graphics.getWidth();
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0.2f, 0, 10);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
game.batch.begin();
game.font.draw(game.batch,playButton,screenWidth/3,screenHeight/2);
game.batch.end();
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
//here, how to detect that the user clicked on the text??
return true;
}
我在屏幕左侧中心附近显示了文字。如何知道用户点击了那个文本?
答案 0 :(得分:1)
您需要创建一个带有文本边界的rectale。为此,您需要GlypLayout来获取文本的高度和宽度。
public class MainMenuScreen implements Screen,InputProcessor {
final MainClass game;
String playButton = "PLAY";
private int screenWidth;
private int screenHeight;
Rectangle recPlayButton;
GlyphLayout layout;
public MainMenuScreen(final MainClass gam){
game=gam;
Gdx.input.setInputProcessor(this);
screenHeight = Gdx.graphics.getHeight();
screenWidth = Gdx.graphics.getWidth();\
layout = new GlyphLayout();
recPlayButton = new Rectangle();
layout.setText(game.font, playButton);
recPlayButton.set(screenWidth / 3, screenHeight / 2, layout.width, layout.height);
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0.2f, 0, 10);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
game.batch.begin();
game.font.draw(game.batch,playButton,screenWidth/3,screenHeight/2);
game.batch.end();
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
Vector3 touchPos = new Vector3(screenX, screenY, 0);
if (recPlayButton.contains(touchPos.x, touchPos.y)) {
Gdx.app.log("Test", "Button was clicked");
return true;
}
else
return false;
return true;
}