How do I center text (Integer/Float) with Python in BGE?


So I have a score counter using a normal text object and it’s always aligned to the left as usual.
I have seen an example on this forum on how to center a string but it doesn’t work for centering a float or integer.

Is there a working script for this?


You can keep text centered by moving the text object left as its size increases. You can get the text size accurately using the blf.dimensions function and scaling it by an appropriate value to convert to blender units (.005 works for centering the text, .01 will work if you want the text to be right aligned). See the attached blend file for an example. Just start the game engine and type some text.

center_text.blend (400.5 KB)

I understand how that works, but I’m not sure how I’d incorporate that to a score counter that adds when an object is hit instead of using the keyboard sensor.

I decided to try and manually move the text to the left using the Motion actuator for every time it goes up a digit, so between 10-99, 100-999 etc.

To my surprise, it worked.

However I’m still interested in seeing if there is an easier method to this since it’s more of a hassle than I originally hoped for.

i know this is old, but i belive you can use a script like this:

from bge import logic
own = logic.getCurrentController().owner
own.localPosition.x = own.dimensions.x * -0.5

bpy.types.Object only works in UPBGE 0.3, not legacy versions.
If one uses 0.3 already, one merely needs to center the text object with the text object setting Center for it’s alignment method:

Python has a centering lib using padding space on each side