Java Read Raw Mouse Input

你离开我真会死。 提交于 2019-12-02 05:01:12

A little code might make the situation clearer, but here's what you can do.

While there are a number of APIs (LWJGL's Mouse interface, as one example) that allow you to directly poll the mouse position, it sounds like overprogramming in your case. First, keep a private field with a reference to that last mouse position. We'll call it x here.

Use a MouseMotionListener, and have it call the same method from mouseMoved and mouseDragged. That method should look something like this.

void controlMethod(MouseEvent event) {
    int newX = event.getXOnScreen();
    int dx = this.x - newX;
    if(dx > 0) **D Key Event**
    else if(dx < 0) ***A Key Event**

    x = newX;
}

That should do the job for you. The only thing you might want to look out for is the mouse straying off of the MouseMotionListener's area; but there are always ways around things like that, and it seems a bit tangential.

As a final note, if you end up with wild swings in mouse control at the beginning of your game loop, consider setting the class field x to an Optional, and use Optional.ifPresent(...) for the dx logic. This will also protect you from data nullification, such as from a focus loss, and I recommend making it a practice.

Best of luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!