开发者

Observing keydown events in JavaScript when two keys are pressed simultaneously

开发者 https://www.devze.com 2023-02-06 10:11 出处:网络
I\'m developing a browser game using JavaScript where the player can move an avatar in all four directions.

I'm developing a browser game using JavaScript where the player can move an avatar in all four directions.

In order to register simultaneous key presses I observe the keydown and keyup events and keep track of the keys that are pressed and released. That way I can move the avatar in a diagonal direction if for example cursor up and cursor right are pressed at the same time.

It's the same p开发者_开发技巧rinciple from this reply here on StackOverflow In Javascript, how do I tell if a user is pressing two keys at the same time? with this demonstration http://jsbin.com/iloxi.

However there's a flaw in that solution which can also be reproduced in the demo. For example press cursor down, then also start pressing cursor right. The box now moves bottom right. Now release cursor right while still pressing cursor down. The box stops moving. What should happen is that the box keeps moving down.

The problem is that JavaScript stops sending cursor down keydown events as soon as cursor right is pressed. Once cursor right is released there's no way of knowing that cursor down is still being pressed.

Is there a solution to this problem?

Update: The problem with the demo is that the box is moved either in the keydown or keyup event listeners. However once the second key is released no more keydown events are fired for the first key. I'm wondering if there's a solution to this or if this is standard JavaScript behavior?

To fix the demo code you would have to call the move() function in a timeout iteration (window.setTimeout()).


Maybe I'm misunderstanding you, but shouldn't you just wait for a keyup event on cursor down? i.e. cursor down is being pressed until you get a keyup for it - you shouldn't be relying on repeated keydown events being sent.

0

精彩评论

暂无评论...
验证码 换一张
取 消