java 读取鼠标,Java读取原始鼠标输入

I'm looking for a way in Java to read in raw mouse input and not just the event listeners. I'll tell you what I'm doing. Essentially, there is a game where if you move the mouse to the right, I want Java to send key signals of the 'd' key being pushed down, and when the mouse is moved to the left, the 'a' key being held down. But, when you move the mouse, the game quickly corrects the mouse position and sends it right back into the middle of the screen. So, if you use mouse listener, you get one event of the mouse being moved to the right, then another quickly following of the mouse being move back to the left. I want to know if I can get data from the mouse without those corrections in the position. Thanks!

解决方案

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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值