2016-07-05 86 views
0

如何檢測文本上的點擊(使用LibGdx)。我只想在用戶點擊文本時更改字體顏色。所以這就是我迄今爲止所獲得的。如何檢測文本點擊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; 
} 

我已經在靠近屏幕中央左側的地方顯示了文本。如何知道用戶點擊該文字?

回答

1

您需要創建一個帶有文本邊界的矩形。爲此,您需要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; 
} 
+0

謝謝,它的工作 –