9
$\begingroup$

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?

$\endgroup$
3

1 Answer 1

3
$\begingroup$

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

$\endgroup$
2
  • $\begingroup$ 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. $\endgroup$
    – Kuba
    Oct 27, 2015 at 7:39
  • $\begingroup$ @Kuba Now you can escape or get into the box by keeping the Ctrl key pressed. $\endgroup$
    – Karsten7
    Oct 27, 2015 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.