Search code examples
androidkotlinlibgdxgame-physicsbox2d

LibGDX BitmapFont not falling down with the body simultaneously


Trying to draw a box with text inside its center, but the text doesn't fall down simultaneously with the body. The text moves a little slower than the polygon, and sometimes the text even not exactly on the right position when body stops moving.

I tried to place a circle inside the polygon, it can moves simultaneously with the polygon.

Please give some advice on doing this, and any other idea to do this without using BitmapFont? Thanks.

fun draw(batch: SpriteBatch, alpha: Float) {
    batch.begin()
    if (!projectionMatrixSet) {
        shapeRenderer.projectionMatrix = batch.projectionMatrix
    }
    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled)
    shapeRenderer.color = dColor
    shapeRenderer.rect(boxBody.position.x - dw, boxBody.position.y - dh, dw*2, dh*2)
    shapeRenderer.end()
    batch.end()

    batch.begin()
    if (!projectionMatrixSet) {
        circleRenderer.projectionMatrix = batch.projectionMatrix
    }
    circleRenderer.begin(ShapeRenderer.ShapeType.Filled)
    circleRenderer.color = Color.WHITE
    circleRenderer.circle(boxBody.position.x , boxBody.position.y, 0.4f)
    circleRenderer.end()
    batch.end()

    batch.begin()
    font.data.setScale(0.05f,0.05f);
    val layout = GlyphLayout(font, "3", Color.BLACK, dw*2 , Align.center, true);
    font.draw(batch, layout, boxBody.position.x - dw, boxBody.position.y + dh)
    batch.end()
}

Solution

  • Call font.setUseIntegerPositions(false) so it isn't rounding off the font position to the nearest whole number worldspace coordinates when it gets drawn. You should also use bilinear or trilinear filtering on your font so it won't look wonky as it moves. So use MipMapLinearLinear for the minifying filter and Linear for the maximizing filter.

    Other problems I notice in your code:

    • Don't surround your shapeRenderer and circleRenderer usage with SpriteBatch begin()/end() calls. They have nothing to do with SpriteBatch. You don't need to begin a SpriteBatch to retrieve its projection matrix. Every call of batch.end() is a potential performance hit.

    • Don't create a GlyphLayout in your draw loop. You're creating a new one on every frame of animation. That will generate a lot of garbage for the GC, which can cause hiccups in your frame rate. Only create a new one when the text changes. And you might consider using a Pool for them if this happens during gameplay.