Search code examples
c#opentk

How to lock cursor to game window?


I'm trying to implement camera movement for an FPS game. I think I've almost got it, but there's just a few more kinks to work out. I've got my mouse movement set up like this:

protected override void OnLoad(EventArgs e)
{
    Mouse.Move += OnMouseMove;
}

void OnMouseMove(object sender, MouseMoveEventArgs e)
{
    _lookDir.X += e.XDelta * _mouseSensitivity;
    _lookDir.Y -= e.YDelta * _mouseSensitivity;
}

Which seems to work pretty well when the mouse is actually inside the window, but as soon as I leave the window it doesn't work. I think what I have to do is somehow constrain the mouse to be inside the window, because even if it triggered a mouse move when my mouse was outside of the window, and still run into the same issue, just at the bounds on my desktop coords instead.

So...how do I do that -- lock my mouse to inside the window? Do I essentially just keep setting the mouse position to the center? If so...how do I set the mouse position? I'm using Windows, but I'd prefer a non-native solution if OpenTK provides it.


Solution

  • Quite simple in OpenTK 3.2

    OpenTK.GameWindow window = new OpenTK.GameWindow();
    window.CursorGrabbed = true;
    

    You can additionally use this snippet to hide the cursor. Just implement it as needed.

    window.Cursor = MouseCursor.Empty;