Se si desidera la ripetizione dei tasti in modo controllabile, si dovrà implementare da soli, come eventi di pressione sono sparati dipende l'idea del sistema operativo di come chiavi devono ripetere. Ciò significa che potrebbero esserci ritardi iniziali e successivi variabili e tenere premuti due tasti contemporaneamente causerà la ripetizione di uno solo di essi.
È necessario tenere un registro di ciascun tasto attualmente premuto e ignorare gli eventi keydown
quando la chiave è già inattiva. Ciò è dovuto al fatto che molti browser generano un evento keydown
e un evento keypress
quando si verifica una ripetizione automatica, e se si sta riproducendo la ripetizione della chiave, è necessario eliminarla.
Ad esempio:
// Keyboard input with customisable repeat (set to 0 for no key repeat)
//
function KeyboardController(keys, repeat) {
// Lookup of key codes to timer ID, or null for no repeat
//
var timers= {};
// When key is pressed and we don't already think it's pressed, call the
// key action callback and set a timer to generate another one after a delay
//
document.onkeydown= function(event) {
var key= (event || window.event).keyCode;
if (!(key in keys))
return true;
if (!(key in timers)) {
timers[key]= null;
keys[key]();
if (repeat!==0)
timers[key]= setInterval(keys[key], repeat);
}
return false;
};
// Cancel timeout and mark key as released on keyup
//
document.onkeyup= function(event) {
var key= (event || window.event).keyCode;
if (key in timers) {
if (timers[key]!==null)
clearInterval(timers[key]);
delete timers[key];
}
};
// When window is unfocused we may not get key events. To prevent this
// causing a key to 'get stuck down', cancel all held keys
//
window.onblur= function() {
for (key in timers)
if (timers[key]!==null)
clearInterval(timers[key]);
timers= {};
};
};
quindi:
// Arrow key movement. Repeat key five times a second
//
KeyboardController({
37: function() { Move(-1, 0); },
38: function() { Move(0, -1); },
39: function() { Move(1, 0); },
40: function() { Move(0, 1); }
}, 200);
Sebbene, molti giochi basati sull'azione hanno un tempo fisso ciclo telaio principale, che si può legare il tasto su/giù movimentazione in .
il tuo codice non funzionerà, questo è sicuro. Non sono sicuro che tu possa provare che due tasti siano premuti contemporaneamente in JS. aspetterò le risposte. –
bene, lo fa in atto, ma non come previsto. Il mio gioco è un gioco basato sul timer, e la sospensione di 1 secondo aspettando che i tasti ripetuti non vadano bene. È frustrante. – alex
perché non provare a utilizzare un approccio basato su flash. un flash swf trasparente che cattura gli eventi e quindi chiama di conseguenza JS. http://www.java2s.com/Code/Flash-Flex-ActionScript/Development/UpLeftSensor.htm –