libgdx添加得分BitmapFont

时间:2017-05-07 12:28:12

标签: java android libgdx

我正在尝试在游戏中添加分数,它应该从分数:0开始,并在每次对象被击中时将分数加1。字体工作,它显示“得分:”[不是0] 碰撞有效。

public class PlayState extends State {
    private int score;
    private String scoreName;
    private BitmapFont font;

    public PlayState(GameStateManager gsm) {
        super(gsm);
        score = 0;
        scoreName = "score: 0";
        font = new BitmapFont(Gdx.files.internal("font.fnt"));
   }

   @Override
   public void update(float dt) {
        handleInput();
        if(ObjectA.collides(ObjectB.getBounds()))
            scoreName = "score: " + ++score;
   }

   @Override
   public void render(SpriteBatch sb) {
        sb.setProjectionMatrix(cam.combined);
        sb.begin();

        font.setColor(0.5f, 0.5f, 0.5f, 0.5f);
        font.getData().setScale(0.4f);
        font.draw(sb, scoreName, cam.position.x, cam.position.y);

        sb.end();
    }

ApplicationAdapter类

public class XY extends ApplicationAdapter {

        public static final int WIDTH = 480;
        public static final int HEIGHT = 800;

        public static final String TITLE = "XY";
        private GameStateManager gsm;
        private SpriteBatch batch;

        @Override
        public void create () {
            batch = new SpriteBatch();
            gsm = new GameStateManager();
            Gdx.gl.glClearColor(1, 0, 0, 1);
            gsm.push(new MenuState(gsm));
        }

        @Override
        public void render () {
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);   
            gsm.update(Gdx.graphics.getDeltaTime());
            gsm.render(batch);       
        }

        @Override
        public void dispose () {
            super.dispose();
        }

GameStateManager

public class GameStateManager {

    private Stack<State> states;

    public GameStateManager(){
        states = new Stack<State>();
    }

    public void push(State state){
        states.push(state);
    }

    public void pop(){
        states.pop().disposed();
    }

    public void set(State state){
        states.pop().disposed();
        states.push(state);
    }

    public void update(float dt){
        states.peek().update(dt);
    }

    public void render(SpriteBatch sb){
        states.peek().render(sb);
    }
}

1 个答案:

答案 0 :(得分:0)

您需要预先增加,以便分数名称具有更新的值。

if(ObjectA.collides(ObjectB.getBounds()))
            scoreName = "score: " + ++score;
            }

您之前的代码将始终在实际得分的后一个点显示得分。

此外,根据您的代码,您需要在主要调用更新后调用始终呈现,否则您的分数将不会更新。最后,当你在类中引用类属性时,请习惯于写this.score