pythonsdlpysdl2

How to get mouse position using PySDL2?


Do not understand at all how to achieve getting the mouse's position except by listening for events, but in the circumstance where the event queue is empty, how is this achieved?

The documentation for pysdl for pygamers suggests using sdl2.mouse.SDL_GetMouseState() (doc here) but this function actially requires the x, y coordinates of the cursor you want to ask about. Meanwhile, calling sdl2.mouse.SDL_GetCursor() returns a cursor object, but I can find no way to get its coordinates from it (ie. it's just wrapping a C object, so it has an empty .__dict__ attribute).

I have been trying everything I can think of but I've never programmed in C before. The simple wrapper function I'm trying to produce is just:

def mouse_pos(self):
            #  ideally, just return <some.path.to.mouse_x_y> 
            event_queue = sdl2.SDL_PumpEvents()
            state = sdl2.mouse.SDL_GetMouseState(None, None)  # just returns 0, so I tried the next few lines
            print state
            for event in event_queue:
                if event.type == sdl2.SDL_MOUSEMOTION:
            #  this works, except if the mouse hasn't moved yet, in which case it's none        
            return [event.x, event.y] 

Solution

  • SDL_GetMouseState() is a wrapper of the SDL2 C function. You thus have to use ctypes to retrieve values from it. The original SDL2 function receives two pointers (x and y) to store the cursor position.

    The snippet below will do the right thing for you:

    import ctypes
    ...
    x, y = ctypes.c_int(0), ctypes.c_int(0) # Create two ctypes values
    # Pass x and y as references (pointers) to SDL_GetMouseState()
    buttonstate = sdl2.mouse.SDL_GetMouseState(ctypes.byref(x), ctypes.byref(y))
    # Print x and y as "native" ctypes values
    print(x, y)
    # Print x and y as Python values
    print(x.value, y.value)
    

    `