I am developing a pong redux in html5 and javascript. I need help modifying it so that upon holding down D, it will subtract 4 from the ball.speedModifier variable, and then add 4 upon releasing D. The reason I don’t just set the modifier back to 0 when the key is released, is because I want to have multiple things changing the modifier at once that stack on top of one another. With my current system for detecting key presses, the addition and subtraction of the variable would repeat at 60 FPS, while I only want it to occur once until the amount is subtracted again.
Here is a pastie of my code:
HTML: http://pastebin.com/txeNftNT
Javascript: http://pastebin.com/scpBqGqx
I think the easiest way to do this would be to track additional properties for each key. Instead of checking just if a key is down or up, you also want to track if they key was down or up on the previous iteration of checkInput(). That way, if the “D” key is down, but it wasn’t down the last iteration, you subtract 4 from ball.speedModifier. Alternatively, if the “D” key is up, but wasn’t up on the last iteration, you then add 4 back to ball.speedModifier.
The final key to making this work is at the end of every checkInput loop, you save out whether each key was down or not. Then on the next loop of checkInput() you’re ready to do your checks again.
The following is just pseudo code, but hopefully gives the idea.
Just in case, I also put together a working example. Do note the three changes. Your pressedKeys is no longer an array, but an object of KeyCodes which correspond to the VALUES of your existing KEY object. And then this key’s value is an object itself with two keys of “wasDown” and “isDown”. I then pre-populate this object at the end of init() and then perform your various checks and updates in checkInput using the new object instead of the array.
http://jsfiddle.net/gUgGf/
Hopefully that helps!