9

I'm trying to use Mathematica to write small games, and I find that it would help to restrict the player's mouse into the game window (just like other games do). Is there any way to achieve this?

I've tried to use this moveMouse function, but I found it not as efficient as I expected, because what I really want is to restrict the cursor inside the window, not to pull it back. In fact, moving the mouse by this function cannot stop the mouse getting out of the window, it just pulls it back only as the function was executed. So I found it doesn't help much for my purpose. Is there any other method (like another java function?) that can actually restrict the mouse?

MrVPlusOne
  • 91
  • 5

1 Answers1

3

Using mouseMove from the answer Silvia linked to in her comment:

Needs["JLink`"]
ReinstallJava[]
robotclass = JavaNew["java.awt.Robot"];

DynamicModule[{mousePosG = {0, 0}, mousePosS, screenPos},
 Column[{
   MouseAppearance[
    Panel[
     Graphics[
      Disk[Dynamic[
        mousePosS = MousePosition[{"ScreenAbsolute", Graphics}, mousePosS]; 
        mousePosG = MousePosition["Graphics", mousePosG]]], 
      PlotRange -> 20, ImageSize -> 200], FrameMargins -> 0, ImageMargins -> 25], ""],
   Row@{Button[ToExpression["\\[" <> "ControlKey" <> "]"], None, 
      Appearance :> If[Dynamic[CurrentValue["ControlKey"]], "Pressed", 
        "DialogBox"]], Dynamic@mousePosG, Dynamic@mousePosS, 
     Dynamic[screenPos = MousePosition["ScreenAbsolute"]],
     DynamicWrapper["", If[screenPos != mousePosS && Not[CurrentValue["ControlKey"]], 
       robotclass[mouseMove[##]] & @@ mousePosS], TrackedSymbols :> {screenPos}]}
   }], Initialization :> (mousePosS = MousePosition["ScreenAbsolute"])
 ]

GIF

One can replace

Disk[Dynamic[
  mousePosS = MousePosition[{"ScreenAbsolute", Graphics}, mousePosS]; 
  mousePosG = MousePosition["Graphics", mousePosG]]]

with, e.g.,

{Arrowheads[.07], 
 Dynamic[Arrow[{# - {-1.5, 3}, #}] &[
   mousePosS = MousePosition[{"ScreenAbsolute", Graphics}, mousePosS];
    mousePosG = MousePosition["Graphics", mousePosG]]]}

to make the cursor look more familiar.

cursor

Karsten7
  • 27,448
  • 5
  • 73
  • 134
  • When mouse isn't initially in the box then I can't get there. When it's outside the notebook I can't get to the notebook. Can't investigate more atm. – Kuba Oct 27 '15 at 07:39
  • @Kuba Now you can escape or get into the box by keeping the Ctrl key pressed. – Karsten7 Oct 27 '15 at 14:05