Discord
Login
Community
DARK THEME

How to lock mouse movement (preferably in Python)

Yep the title explained it all

Do you want the mouse to stay in the game area?

If so, read this thread. Doemo in Javascript. If you can combine Python and javescript, I think it will work. I've never written in Python, so don't ask how to connect it.

https://microstudio.dev/community/questions/mouse-lock-and-mouse-hide/924/

https://microstudio.dev/i/Loginus/pointerlock/

I remember seeing that thread with the mouse lock, but no it does not work. I will attempt to translate it to python

It does not work at all, even with my attempt to translate JavaScript to Python.

You can access browser DOM elements like window , document in Python??

def updatePosition(e):
  global x, y;
  x += e.movementX;
  y += e.movementY;
  print( x );
  pass

def init():
  global canvas
  canvas = window.player.runtime.screen.canvas
  canvas.addEventListener("mousemove", updatePosition, 0);
#  canvas.addEventListener("click", canvas.requestPointerLock() );
  pass

def update():
  pass

def draw():
  pass

I see that this code captures the mouse event (moving over the area where the program is running).

Mouse event capture works.

However, there are errors in the console.

Are you able to improve the code?

I corrected the code.

When I run the program and spam the mouse button in the program area, it captures both events (moving the mouse and locking the cursor in the work area).

However, when I restart the program and do not spam the mouse button at the beginning, it will only capture the event related to the mouse movement (the mouse will not be locked in the workspace).

I don't know why this happens - maybe it will be different for you.

My first Python code :-)

def update_position(event):
  global x, y
  x += event.movementX
  y += event.movementY  
  print("x:", x)
  pass

def init():
  global x, y
  x = 0
  y = 0
  #= 0, 0

  # canvas = document["canvas"]
  
  global canvas
  canvas = window.player.runtime.screen.canvas
  canvas.bind("mousemove", update_position)
  canvas.bind("click", canvas.requestPointerLock())
  pass


def update():
    pass

def draw():
    pass

Edit

Eeeee

I figured out this problem.

Yes the code is correct.


def update_position(event):
  global x, y
  x += event.movementX
  y += event.movementY  
  print("x:", x)
  pass

def lock_pointer(event):
    canvas.requestPointerLock()  
    
def init():
  global x, y
  x = 0
  y = 0
  #= 0, 0

  # canvas = document["canvas"]
  
  global canvas
  canvas = window.player.runtime.screen.canvas
  canvas.bind("mousemove", update_position)
  canvas.bind("click", lock_pointer)
  pass


def update():
    pass

def draw():
    pass

Good job on writing python code

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community