What you're missing is a "game loop".
Instead of reacting directly to key down or up in deciding whether and when to move your shape around the canvas, you need to use the key events to keep track of which keys are down at any given moment, and then check the key state from a setTimeout()
-based loop running independent of the key events.
You've started to do that with your keys
variable keeping track of whether a given key is down at any moment:
// in keydown
keys[event.which] = true;
// in keyup
delete keys[event.which];
...except that event
is not defined - you need to make it a parameter of the event handler, and also none of your code ever actually checks the values in keys
.
Here's a simplified version of what I'm talking about:
$(document).ready(function(e){
var keys = {};
$("input").keydown(function(event){
keys[event.which] = true;
}).keyup(function(event){
delete keys[event.which];
});
function gameLoop() {
// w for north
if (keys[87]) {
north++;
flipednorth--;
}
//press s for south
if (keys[83]) {
north--;
flipednorth++;
}
// etc. for other keys
// code to move objects and repaint canvas goes here
setTimeout(gameLoop, 20);
}
gameLoop();
});
Demo: http://jsfiddle.net/ktHdD/1/
The gameLoop()
function will run ever 20 milliseconds or so (you can vary this as needed, but that's fast enough for reasonably smooth animation). Each time it runs it checks if any keys are down and if so adjusts the relevant position variables and repaints. If you have other objects that move around automatically (e.g., in a game there might be bad guys) you'd update them in the gameLoop()
function too.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…