Onscreen Text overlapping on each other instead of replacing

I want to see the current co-ordinates using current coordinates so i am using the following code but the text is overlapping so how do i coorect this?

Code

from direct.showbase.ShowBase import ShowBase
from direct.gui.OnscreenText import OnscreenText
from panda3d.core import *

class example(ShowBase):
    def __init__(self):
        super().__init__()
        self.pd = self.loader.loadModel("models\panda")
        self.pd.setScale(0.05)
        self.pd.reparentTo(render)
        self.x = 0
        self.z = 0
        self.i = 0
        self.taskMgr.add(self.moving, "moving")

    def moving(self, task):
        dt = globalClock.getFrameTime()
        self.pd.setPos(self.x+self.i, 0, self.z+self.i)
        textt = str(self.pd.getPos())
        self.textObject = OnscreenText(text=textt, pos=(0, -0.8), scale=0.07, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=1)
        self.i += 0.01
        return task.cont

if __name__ == '__main__':
    viz = example()
    viz.run()

Screenshot

Here is the screenshot:


How do i correct it?

Call destroy() on the previous text object before creating the new one.

But then the text is not displayed at all.

Screenshot

What I’d suggest is that, instead of creating a new OnscreenText for each update, you create just one during initialisation, and then alter its text as called for. Something like this (using a simplified example for convenience and clarity):

    def __init__(self):
        # ... Other initialisation here ...
        
        # Create our OnscreenText object:
        self.coordinateDisplay = OnscreenText(text = "",
                                              mayChange = True,
                                              scale = 0.05)

        # Start up our task:
        self.taskMgr.add(self.updateCoordDisplay, "update coord display")

    def updateCoordDisplay(self, task):
        # Get our new text...
        coordText = str(self.pd.getPos())
        # ... And set our OnscreenText object to display it:
        self.coordinateDisplay.setText(coordText)

        return task.cont

Where did you place the destroy line then?

Before the self.i line

Thanks Got it!!

1 Like

That would delete the new one, not the old one, I believe.

If you’d placed the “destroy” line instead before you created the new OnscreenText, then rdb’s suggestion may well have worked.

I’m glad of it! :slight_smile:

That makes sense!!! Thanks for this!!

1 Like