如何在libgdx的舞台上绘制位图字体?

8

这是我在Libgdx游戏中我的关卡上的当前渲染方法。我正在尝试在我的关卡的右上角绘制BitmapFont,但我得到的只是一堆白色方框。

 @Override
    public void render(
            float delta ) {
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

        this.getBatch().begin();

            //myScore.getCurrent() returns a String with the current Score
        font.draw(this.getBatch(), "Score: 0" + myScore.getCurrent(), 600, 500);
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
        this.getBatch().end();
        }

我想将得分字体添加到某个角色中,然后执行scene.addActor(myScore),但我不知道如何做。 我遵循Steigert的教程创建了主游戏类来实例化场景、字体,在抽象级别类中,该类被这个级别继承。 目前为止,我没有使用任何自定义字体,只是使用空的new BitmapFont(); 来使用默认Arial字体。以后我想使用我自己更加花哨的字体。
4个回答

12

尝试将 font.draw 移动到 stage.draw 之后。将其添加到 Actor 中会非常简单,只需创建一个新类并扩展 Actor,就像这样:

import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Actor;

public class Text extends Actor {

    BitmapFont font;
    Score myScore;      //I assumed you have some object 
                        //that you use to access score.
                        //Remember to pass this in!
    public Text(Score myScore){
        font = new BitmapFont();
            font.setColor(0.5f,0.4f,0,1);   //Brown is an underated Colour
    }


    @Override
    public void draw(SpriteBatch batch, float parentAlpha) {
         font.draw(batch, "Score: 0" + myScore.getCurrent(), 0, 0);
         //Also remember that an actor uses local coordinates for drawing within
         //itself!
    }

    @Override
    public Actor hit(float x, float y) {
        // TODO Auto-generated method stub
        return null;
    }

}
希望这可以帮到您!

编辑1:也可以尝试System.out.println(myScore.getCurrentScore());,以确保那不是问题。您只需让它返回一个浮点数或整数,当您执行"Score:"+部分时,它会自动将其转换为字符串

1
谢谢!这可能会解决问题,但我找到了一个非常棒的工具叫做 Label 它刚好符合我的需求。我目前将Label扩展为我的得分,并将其作为常规演员添加到舞台上。运行得很好。 - Peter Poliwoda

3

好的,在这种情况下,您可能需要先调用 this.getBatch().end。像这样:

mSpriteBatch.begin();
mStage.draw();
mSpriteBatch.end();
//Here to draw a BitmapFont
mSpriteBatch.begin();
mBitmapFont.draw(mSpriteBatch,"FPS",10,30);
mSpriteBatch.end();

我也不知道为什么,但这对我有用。


2

我曾经遇到过类似的白框问题,解决方法是在开始绘制阶段之前关闭批处理。这是因为stage.draw()会启动另一个批处理并使之前未以end()结束的批处理失效。

因此,在当前示例中,我会将this.getBatch().end()移动到绘制阶段之前:

    ...
    font.draw(this.getBatch(), "Score: 0" + myScore.getCurrent(), 600, 500);
    this.getBatch().end();
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
    }

-2
如果您正在使用Scene2D,请尝试使用stage和actors。无需编写冗长的代码,检查MTX插件非常容易使用。您可以创建一个令人惊叹的用户体验。

http://moribitotechx.blogspot.co.uk/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接