Search code examples
javakotlinlibgdxmouse-cursor

libGDX's stops being able to catch cursor after entering fullscreen


I'm writing a little libGDX game. Capturing the cursor with setCursorCatched(boolean) works perfectly at first (hides the cursor symbol and won't let me escape the window) but then breaks:

  • After I enter fullscreen with F and then exit with G, the cursor can escape on all sides.
  • After I enter fullscreen with F with 2 monitors, I can also escape to my 2nd monitor.
  • Using setCursorPosition every frame does not mitigate this issue.

Full minimal reproducible example (see also my other question):

package xjcl.extracredits2020

import com.badlogic.gdx.*

class RangeAnxietyGame : ApplicationAdapter() {
    override fun create() {
        Gdx.input.apply { isCursorCatched = true }
    }

    override fun render() {
        if (Gdx.input.isKeyPressed(Input.Keys.F))
            Gdx.graphics.setFullscreenMode(Gdx.graphics.displayMode)
        if (Gdx.input.isKeyPressed(Input.Keys.G))
            Gdx.graphics.setWindowedMode(1280, 720)
        if (Gdx.input.isKeyPressed(Input.Keys.ESCAPE))
            Gdx.app.exit()

        Gdx.input.setCursorPosition(Gdx.graphics.width/2, Gdx.graphics.height/2)
    }
}

Is there any way to force the cursor to stay captured by the libGDX window?


Solution

  • As suggested by @Tenfour04, switching from lwjgl to lwjgl3 eliminates the issue!

    In build.gradle change the first into the second block:

    api "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"
    
    api "com.badlogicgames.gdx:gdx-backend-lwjgl3:$gdxVersion"
    

    Also adjust your imports (e.g. in the DesktopLauncher class):

    import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
    import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
    
    import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application;
    import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration;
    

    In my case I also needed to update the config of the DesktopLauncher:

    LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
    config.samples = 8;
    config.height = 720;
    config.width = 1280;
    config.vSyncEnabled = true;
    new LwjglApplication(new RangeAnxietyGame(), config);
    
    Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration();
    config.setBackBufferConfig(8, 8, 8, 8, 16, 0, 8);
    config.setWindowedMode(1280, 720);
    config.useVsync(true);
    new Lwjgl3Application(new RangeAnxietyGame(), config);