python snippet: custom mouse cursor


have you ever wanted to have a custom mouse cursor in your game? Well it’s very easy, with the right code.

import bge

cont = bge.logic.getCurrentController()
own = cont.owner

def set_custom_mouse_cursor(camera,cursor_object):
    mouse_position = bge.logic.mouse.position     
    screen_vector = camera.getScreenVect(mouse_position[0],mouse_position[1]) 
    screen_vector.negate()            
    screen_ray = camera.worldPosition + screen_vector 
    screen_orientation = screen_ray.to_track_quat("Z", "Y")
    cursor_object.worldPosition = screen_ray
    cursor_object.worldOrientation = screen_orientation
    
camera = own
cursor_object = own.children[0] 
    
set_custom_mouse_cursor(camera,cursor_object)   

All you need is a camera and an object to use as a cursor. Make sure the object is quite small because it’ll be very close to the camera. Also make sure not to set your near clipping value too low, or you won’t be able to see it.

Here’s a demo of how to use it:
custom_cursor.blend (479 KB)

Ah, I was using this today and realized you don’t need the orientation part of the script unless you want a 3d cursor which points to the center of the screen. I’ve updated the script in the first post so it works well now.

you only need:

import bge

cont = bge.logic.getCurrentController()
own = cont.owner

def set_custom_mouse_cursor(camera,cursor_object):
    mouse_position = bge.logic.mouse.position     
    screen_vector = camera.getScreenVect(mouse_position[0],mouse_position[1]) 
    screen_ray = camera.worldPosition - screen_vector 
    cursor_object.worldPosition = screen_ray
    
camera = own
cursor_object = own.children[0] 
    
set_custom_mouse_cursor(camera,cursor_object)   

You also don’t need to negate the vector if you subtract the vector instead of adding it.

niuce thanks…