How to get mouse cursor position relative to the world position?

How can I get the X and Y world position based on a mouse position?

own["X_MOUSE"] = logic.mouse.position[0]
own["Y_MOUSE"] = logic.mouse.position[1]

This gives me just the position relative to the screen.

Try using the Mouse Over or Mouse Over Any sensor. You can also raycast from the camera, but the sensor method is a lot easier.

Example file

ex_mouseposition.blend (113.6 KB)

Example script

import bge

cont = bge.logic.getCurrentController()
own = cont.owner
mouseOver = cont.sensors["MouseOver"]

if mouseOver.positive:
    own["X_MOUSE"] = mouseOver.hitPosition.x
    own["Y_MOUSE"] = mouseOver.hitPosition.y
    own.worldPosition = mouseOver.hitPosition
1 Like

Thanks, this works fine, but it requires a static plane object to work.
Is there no other way?

What you want to do?

If it didn’t collide with anything then your mouse location would be infinity distance from the camera. Most people want to know where the mouse is on their terrain, or on a object.

Ok, I get it. I have managed to make it with a static plane object.
I only wondered if it could have been done in python only.

you can use RayCast to get a position without mouse sensors - the mouse sensor is very simple and convenient if you leave the mouse sensor properties line empty, you can always check the objects that fall under this sensor and get them, as well as get the position of the mouse cursor at the location of the collision registration, to get the world coordinates of the mouse, you need an object on which you get the position of the point of space on the object

Randomly throwing this out here.

KX_Camera.owner.getScreenPosition([bge.logic.mouse.position[0],bge.logic.mouse.position[1],0])

This is the mouse position while taking into account the 3D matrix position I believe …

1 Like