Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

libgdx on desktop - Determine if mouse outside window

Tags:

java

libgdx

I need to be able to check if the mouse is outside the window of my libgdx app running on a windows desktop.

Gdx.input.getX() and Gdx.input.getY() are constrained to my app window on Windows (but not on Mac).

I tried Gdx.input.setCatched(true) which does make it unconstrained, but it also binds the mouse entirely to my app. So Windows doesn't get any mouse events until I alt+tab to a different app.

I've also tried writing an InputProcessor, but mouseMoved only gets fired within the window. TouchDragged works outside, but of course that only gets fired when the mouse button was pressed and held within the window.

Any help greatly appreciated.

like image 724
Phil Anderson Avatar asked Jun 02 '15 10:06

Phil Anderson


1 Answers

I found a way, but by golly it's a bit of a faff. It takes advantage of the lwjgl backend Mouse.isInsideWindow() method (thanks to Khopa for the link).

If anyone's interested, here it is...

Create an interface in your libgdx core module...

public interface MouseWindowQuery {

    public boolean isMouseInsideWindow();
}

Add a MouseWindowQuery field to your main AplicationListener class (this'll be the class that extends Game for a lot of folks) and save it away somewhere...

public class SampleApp extends Game
{
    private MouseWindowQuery mouseWindowQuery;

    public FirstLibgdxApp(MouseWindowQuery mouseWindowQuery) {
        this.mouseWindowQuery= mouseWindowQuery;
    }
    ...
}

Now in the desktop module you can implement the interface as follows...

public class MouseWindowQueryImpl implements MouseWindowQuery {

    @Override
    public boolean isMouseInsideWindow() {

        return Mouse.isInsideWindow();
    }
}

Finally, pass this in to your main ApplicationListener class from your DesktopStarter class (the one with the main method).

Now you can use the instance you passed in however you wish.

If you have other modules (e.g. Android) you'd have to pass in a null implementation instead (i.e. an implementation of MouseWindowQuery that just returned false).

In case you're wondering, the interface and implementations are necessary in order to avoid introducing a dependency on desktop from core.

Phew! I realy hope that helps somebody!

like image 120
Phil Anderson Avatar answered Sep 25 '22 22:09

Phil Anderson