java keylistener,Java-KeyListener:如何触发事件?

本文讨论了在游戏开发中处理键盘输入的问题,特别是如何在用户同时按多个键时正确移动角色。作者指出,直接在keyPressed方法中调用运动方法会导致只能响应最后一个按下键的状态。解决方案是将更新移动状态的逻辑移到游戏循环中,通过一个update方法检查当前哪些键被按下,并相应地更新角色位置。这种方法确保了可以同时处理多个按键事件,并且在键释放时能正确更新键的状态。
摘要由CSDN通过智能技术生成

i programming the control for a very simple game in a KeyListener. Ive got the Following Problem.

I did something like this(only an easy example not my implemented code):

public void keyPressed(KeyEvent e) {

if (e.getKeyCode() == KeyEvent.VK_LEFT) {

leftPressed = true;

Methodxyz(leftpressed,rightpressed,uppressed)

}

if (e.getKeyCode() == KeyEvent.VK_RIGHT) {

rightPressed = true;

Methodxyz(leftpressed,rightpressed,uppressed)

}

if (e.getKeyCode() == KeyEvent.VK_UP) {

upPressed = true;

Methodxyz(leftpressed,rightpressed,uppressed)

}

}

public void keyReleased(KeyEvent e) {

if (e.getKeyCode() == KeyEvent.VK_LEFT) {

leftPressed = false;

}

if (e.getKeyCode() == KeyEvent.VK_RIGHT) {

rightPressed = false;

}

if (e.getKeyCode() == KeyEvent.VK_UP) {

upPressed = false;

}

}

If i press 2 keys(left,up) at the same time youre able to move the charachter diagonal. The thing is the listener works with the last pressed KeyEvent so if i press left then up, but didnt release the left and release up, the object wont be move(left is still pressed).

How can i handle that? Is it possible to fire keypressed events in my keypressed method of my keylistener til leftpressed is false?

Any ideas?

thanks in advance

解决方案

Don't call the movement method inside the keypress method, instead whenever you call the updates in your gameloop also call an update method in your inputlistener that checks which keys have been pressed, this will allow you to have multiple keypresses at the same time, keypresses that will be set to false once the key is released, like so:

In your inputhandler:

public void update() {

if (up == true) {

SomeMethod(Key.UP);

}

if (down == true) {

SomeMethod(Key.DOWN);

}

if (left == true) {

someMethod(Key.LEFT);

}

if (right == true) {

someMethod(Key.RIGHT);

}

}

public void keyReleased(KeyEvent e) {

switch (e.getKeyCode()) {

case KeyEvent.VK_S:

down = false;

break;

case KeyEvent.VK_W:

up = false;

break;

case KeyEvent.VK_A:

left = false;

break;

case KeyEvent.VK_D:

right = false;

break;

}

}

public void keyPressed(KeyEvent e) {

switch (e.getKeyCode()) {

case KeyEvent.VK_S:

down = true;

break;

case KeyEvent.VK_W:

up = true;

break;

case KeyEvent.VK_A:

left = true;

break;

case KeyEvent.VK_D:

right = true;

break;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值