Determine if mouse outside window

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.


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 (eg Android) you'd have to pass in a null implementation instead (ie 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!

链接地址: http://www.djcxy.com/p/26850.html

上一篇: AngularJS以编程方式从服务调用过滤器(按自定义过滤器排序)

下一篇: 确定鼠标是否在窗外