How do i draw mouse coordinates to the screen.

Ok i have designed a cool way of controlling my ship but i will need some output (text on the screen) to help me tweak it to make it realistic. So i need to first of all get my mouse coordnintes on the screen. I have put this line of code into my code:

textObject = OnscreenText(text = 'Mouse X position: ' + base.mouseWatcherNode.getMouseX()
 , pos = (-0.5, 0.02), scale = 0.07)

but this code didnt render anything to the screen. What am i doing wrong?

.reparentTo(render/render2d/aspect2d)? I’m always forgetting to do that…

OnscreenText is parented to aspect2d by default.

okay… and the aspect2d coordinate space is -1 to 1 on both axes? If so, I’m not seeing anything flagrantly wrong with that line in particular.

You might try a simple print statement to verify that execution is even reaching the textObject declaration (and if that’s in a loop, you’re going to want to reconsider how you set it up, otherwise you’re going to have a zillion rogue textNodes building up in the scene over time).

ok my code isnt in a loop. There is only one big list of code that it goes through so i dont see how this isnt working :

if base.mouseWatcherNode.hasMouse():
    print('Mouse X Position: ' + base.mouseWatcherNode.getMouseX() )
    mouseXPos = OnscreenText(text = 'Mouse X position: ' + base.mouseWatcherNode.getMouseX() , pos = (-0.5, 0.02), scale = 1) 

Now… the print isnt even printing anything out so i think its a problem with the first if statement. Is there anything wrong with it?

Well, if you can verify that it’s getting to the point right before the if statement, and it’s not executing anything in the if statement, than the if condition is failing. If that’s the case, I’ve never used mouseWatcherNode much, but I’d guess there’s something you need to do to prime/initialize/enable it if it’s not detecting your mouse by default.

Well ill post my code i guess in case anyone willing to help me needs to look at it:


import direct.directbase.DirectStart
from direct.gui.OnscreenText import OnscreenText



gamePlaying = True


class area:
    def _init_(self):
        self.areaName = "untitled"
       
        self.type = "system" 
        
        self.planetList = []
        
        self.star = ''

        self.backGroundMesh = loader.loadModel("Models/Planets/solar_sky_sphere")
        
        self.tex = "stars"
        
        self.backGroundTex =  loader.loadTexture("Models/Planets/" + self.tex + "_tex.jpg")
       
    def renderArea(self):
        for p in self.planetList:
            planet.planetRender(p)
            
            self.backGroundMesh.setTexture(self.backGroundTex, 1)
            self.backGroundMesh.reparentTo(render)
            self.backGroundMesh.setScale(1000)
            
        star.starRender(self.star)

   
class star:
    def _init_(self):
        self.starName = "sun"
       
        self.area = sol
       
        self.xPos = 0

        self.yPos = 0
       
        self.zPos = 0
       
        self.position = (self.xPos, self.yPos, self.zPos)
       
        self.size = (100)
       
        self.starType = "yellow"
        
        self.sphere = loader.loadModel("Models/Planets/planet_sphere")
       
        self.tex = loader.loadTexture("Models/Planets/sun_" + self.starType + "_tex.jpg")

    def starRender(self):
        if currentArea == self.area:
            
            self.sphere.setTexture(self.tex, 1)
            self.sphere.setPos(self.position)
            self.sphere.setScale(self.size)
            self.sphere.reparentTo(render)

class planet:
    def _init_(self):
        self.planetName = "earth"
       
        self.area = sol
       
        self.xPos = 0

        self.yPos = 150
       
        self.zPos = 20
       
        self.position = (self.xPos, self.yPos, self.zPos)
       
        self.size = (15,15,15)
       
        self.planetType = "earth"
        
        self.sphere = loader.loadModel("Models/Planets/planet_sphere")
       
        self.tex = loader.loadTexture("Models/Planets/" + self.planetType + "_tex.jpg")
       
       
    def planetRender(self):
        if currentArea == self.area:
            
            self.sphere.setTexture(self.tex, 1)
            self.sphere.setPos(self.position)
            self.sphere.setScale(self.size)
            self.sphere.reparentTo(render)
           
           

           

       
class ship:
    def __init__(self):
        self.shipName = "fighter"

        self.xPos = 0

        self.yPos = 0
       
        self.zPos = 0

        self.position = (self.xPos, self.yPos, self.zPos)
       
        self.size = (0.25,0.25,0.25)

        self.hull = 100

        self.hullMax = 1000

        self.energy = 1000

        self.energyMax = 1000

        self.engineSpeed = 5
       
        self.turningSpeed = 5

        self.thrustingSpeed = 0

        self.thrustingSpeedMax = 10

        self.primaryWeapon = 1

        self.secondaryWeapon = 0

        self.secondaryWeaponMax = 0

        self.area = sol

        self.isComp = True;

    def shipRender(self):
        if currentArea == self.area:
            self.ship = loader.loadModel("Models/Ships/" + self.shipName)
            self.ship.setPos(self.position)
            self.ship.setScale(self.size)
            self.ship.reparentTo(render)
#    def playerTurn(self, mouseX, MouseY):
      
     
sol = area()
area._init_(sol)

currentArea = sol
       
# setting up the player
playerShip = ship()
playerShip.xPos = 0
playerShip.yPos = 200
playerShip.zPos = 0
playerShip.position = (playerShip.xPos, playerShip.yPos, playerShip.zPos)
playerShip.turningSpeed = 90
playerShip.isComp = False
# setting up the planets & stars

sun = star()
star._init_(sun)

earth = planet()
planet._init_(earth)

sol.planetList = [earth]
sol.star = sun

area.renderArea(sol)




base.disableMouse()

      



ship.shipRender(playerShip)

playerShip.ship.setHpr(0,0,0)

camera.setPos(playerShip.ship , 0, - 150, 0 )
camera.setHpr(playerShip.ship.getHpr())     

if base.mouseWatcherNode.hasMouse():
    print('Mouse X Position: ' + base.mouseWatcherNode.getMouseX() )
    mouseXPos = OnscreenText(text = 'Mouse X position: ' + base.mouseWatcherNode.getMouseX() , pos = (-0.5, 0.02), scale = 1) 

run() 

Even if you take away the if statement it still gives you a crazy error:
AssertionError: _has_mouse at line 65 of built/include/mouseWatcher.I

I didnt do any changes to the config files, in fact, i dont even know how to yet :open_mouth:
so am i supposed to change something in it to fix my problem?
Thanks for any help :exclamation: :exclamation: :exclamation:

The text is never created because hasMouse() returns False, i.e. the mouse is not found within the frame.

What you should be doing is listening for mouse movement, and then destroy() and create a new text overlay every time the mouse X position changes.

EDIT: Here’s some code that might help…

import direct.directbase.DirectStart
from pandac.PandaModules import *
import sys
from direct.gui.OnscreenText import OnscreenText
from direct.task import Task

hasMouse = False
lastX = 0
lastY = 0
text = None
font = loader.loadFont("cmss12")

def mouseMoved(x, y):
    updateText('Mouse X position: %g' % x)
    
def mouseLost():
    updateText('Mouse lost')

def updateText(msg):
    global text
    if text is not None:
        text.destroy()
    text = OnscreenText(text=msg, style=1, font=font,
                    fg=(0,0,0,1), align=TextNode.ALeft, pos=(-1.15, .8), scale=.07)

#Task to move the camera
def MouseMotion(task):
    global lastX, lastY, hasMouse
    if base.mouseWatcherNode.hasMouse():
        hasMouse = True
        x = base.mouseWatcherNode.getMouseX()
        y = base.mouseWatcherNode.getMouseY()
        if x!=lastX or y!=lastY:
            mouseMoved(x, y)
            lastX = x
            lastY = y
    elif hasMouse:
        hasMouse = False
        mouseLost()
    return Task.cont

taskMgr.add(MouseMotion, 'MouseMotion')
updateText('Mouse lost')

run()

Thanks davedes problem solved!

edit; double post

a thinner and fixed version of the code above:

import direct.directbase.DirectStart 
from pandac.PandaModules import *
from direct.gui.OnscreenText import OnscreenText
from direct.task import Task

text = OnscreenText(text='', style=1, fg=(0,0,0,1), align=TextNode.ALeft, pos=(-1.15, .8), scale=.07)

def mouseMoved(x, y):
    updateText('Mouse pos (%0.3f, %0.3f)' % (x,y))
    
def mouseLost():
    updateText('Mouse lost')

def updateText(msg):
  global text
  text.setText(msg)

#Task to move the camera
def MouseMotion(task):
  if base.mouseWatcherNode.hasMouse():
    x = base.mouseWatcherNode.getMouseX()
    y = base.mouseWatcherNode.getMouseY()
    mouseMoved(x, y)
  else:
    mouseLost()
  return Task.cont

taskMgr.add(MouseMotion, 'MouseMotion')

run()

PS: you must never put a OnscreenText in a loop

Interesting. Some of the samples should be updated, as they use destroy()/recreate. e.g. Fireflies tutorial.