Search code examples
javalibgdx

Text not displaying in LibGdx Java


I am trying to add text for debugging purposes in my program. I call the players debugDraw method like so in the main class:

public void create () {

    //Initialize essentials
    cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    cam.setToOrtho(false);

    rend = new ShapeRenderer();
    rend.setAutoShapeType(true);

    batch = new SpriteBatch();



    // Initialize Entities
    player = new Player(new Vector2(100, 100), new Vector2(100,100));
    enemy = new Enemy(new Vector2(100, 100), new Vector2(100,10));
}

@Override
public void render () {
    //Update player
    player.update();
    //Update camera then set matrix of batch
    cam.update();
    batch.setTransformMatrix(cam.combined);

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    // ShapeRenderer begin
    rend.begin();
    player.render(rend);
    enemy.render(rend);
    rend.end();
    // ShapeRenderer end

    // SpriteBatch begin
    batch.begin();
    player.renderDebugText(batch);
    batch.end();
    // SpriteBatch end

}

Here is the entity class which is the parent class to player:

 public Entity(Vector2 coords, Vector2 dims){
    //Assign constructors
    position = coords;
    dim = dims;

    //For debugging purposes of all entities
    debugText = new BitmapFont();
    debugText.setColor(Color.WHITE);
}


public void renderDebugText(SpriteBatch batch){
    debugText.draw(batch, "Vel.x: " + vel.x, 100, 100);

}

However when I run the program, I just get my normal screen with no text at all. I can't seem to figure out why this isn't working. Any help is extremely appreciated.


Solution

  • Nothing immediately looks wrong with the code you posted, so here's a few ideas;

    The default BitmapFont is 15pt, if this is drawn at 15px height then it could be very small if you force your game to a high resolution, like Full-HD. My current project is Full-HD and the font I use looks just about right at 45px, so you could try scaling yours by a factor of 3 or 4. E.g. use this after initialising your font;

    bitmapFont.getData().setScale(3);
    

    Your Camera should also have the virtual/viewport dimensions, so if you are forcing a particular resolution then you should pass in your virtual dimensions instead.

    As @Tenfour04 has suggested, you should try to avoid multiple instances of the same font, so instead of initialising your font in the Entity class, initialise it in your main game and pass it through the Entity constructor. I can't see how this would fix your issue though as this would be purely for performance.