libGDX - Add scores & display it at top left corner of the screen?

本秂侑毒 提交于 2019-12-03 22:47:59

Here is a link to a libGDX users wiki that I found helpful when I had encountered the same question for a Pong remake.

To display the score, the tools that you need are: an int variable to keep score, a String or CharacterSequence variable to help display the score (I'll use a String), and a BitmapFont which is used to display a font type.

First step: declare all of these tools.

private int score;
private String yourScoreName;
BitmapFont yourBitmapFontName;

Second step: initialize them in the create method

public void create()     
    score = 0;
    yourScoreName = "score: 0";
    yourBitmapFontName = new BitmapFont();

Tertiary step: increment the score variable and change the yourScoreName String variable in your collision logic method (when the raindrop overlaps the bucket).

if(raindrop.overlaps(bucket)) {
     score++;
     yourScoreName = "score: " + score;
     dropSound.play();
     iter.remove();

Fourth step: In the render() method, set the color of the font and call the draw method on your BitmapFont between spriteBatch.begin and spriteBatch.end.

batch.begin(); 
yourBitmapFontName.setColor(1.0f, 1.0f, 1.0f, 1.0f);
yourBitmapFontName.draw(batch, yourScoreName, 25, 100); 
batch.end();

Play with: the parameters in the font.setColor() method so that you can see them in contrast to your background color, the number parameters in the font.draw() method to get the score related textures displayed in the top left corner (the last two number parameters in the font.draw() method represent the x and y coordinates of the score texture).

Fifth step: run it, then smile.

The same logic will apply to displaying, "GAME OVER." For heuristic purposes, I'll leave the creation of the logic up to you.

Read the documentation in the link to gain a deeper understanding of the magic.

To display the score you could create a stage.

Stage stage = new Stage();
stage = new Stage();
stage.setCamera(cam);
stage.setViewport(WIDTH, HEIGHT, false);

Then you'll have to create like a label, and a text font. So you can look that up on the libgdx wiki for details.

Label text;
LabelStyle textStyle;
BitmapFont font = new BitmapFont();
//font.setUseIntegerPositions(false);(Optional)

textStyle = new LabelStyle();
textStyle.font = font;

text = new Label("Gamever",textStyle);
text.setBounds(0,.2f,Room.WIDTH,2);
text.setFontScale(1f,1f);

Then just add that to the stage when the game is lost using:

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