Centring a billboard above a geometry

@Override
    public void simpleInitApp() {

        Node newPlayerNode = new Node ();
        //
        Box b = new Box(1, 1, 1);
        Geometry geom = new Geometry("Box", b);
        Material mat = new Material(assetManager, "Common/MatDefs/Misc/ShowNormals.j3md");
        geom.setMaterial(mat);
        //
        newPlayerNode.attachChild(geom); 
        
        Vector3f v = geom.getLocalTranslation().add(0f, 1.5f, 0f); 
        BitmapFont myFont = assetManager.loadFont("Interface/Fonts/Courier10Pitch.fnt");
        BitmapText hudText;
        hudText = new BitmapText(myFont, false);
        hudText.setName("playerName"); 
        hudText.setColor(ColorRGBA.Yellow);
        hudText.scale(0.02f);
        hudText.setText("player name");
        hudText.setQueueBucket(Bucket.Transparent);
        hudText.setLocalTranslation(v); 
        //
        Node billboardNode = new Node("playerName_billboard");
        BillboardControl control = new BillboardControl();
        billboardNode.addControl(control);
        billboardNode.attachChild(hudText);
        
        newPlayerNode.attachChild(billboardNode); 

        rootNode.attachChild(newPlayerNode);
    }

I have been trying to centre the text above a geometry unsuccessfully for a few days.

I am still very much a jMonkey-n00b so don’t be afraid of putting my right on even-this simple piece of code or put me right on how to properly use nodes. Thanks.

Note:
The above code will not work unless you have a font in your assets/Interface directory. I am using Oracle JDK 8.n.

Best regards

Two ways:

  1. easiest: hudText.center() then move it up a bit if you like
  2. set hudTexts horizontal alignment to center and give it a box based on the text size: http://javadoc.jmonkeyengine.org/com/jme3/font/BitmapText.html#setBox(com.jme3.font.Rectangle)

Thanks for your reply pspeed. I’ll check it out.

Best regards

Thanks again pspeed, your second suggestion sorted it for me. I added the following code to the bottom of the hudText block:

hudText.setAlignment(BitmapFont.Align.Left);
hudText.setBox(new Rectangle (-(hudText.getLineWidth()/2),0,
                              hudText.getLineWidth(), hudText.getHeight()));

Note:
BitmapFont.Align.Center has the same effect as as …Align.Left so I’ve set the X coordinate of the Rectangle to be half the width of the text object and set alignment to: Left

Width of the Rectangle is set to the full size of the text object to prevent the text from word-wrapping.

The Rectangle is the com.jme3.font.Rectangle btw.