Estoy creando un juego FPS en 3D con Three.js.
Cuando uso un arma automática completa, quiero que dispare continuamente desde el segundo en que mantienes presionada la tecla "f".
Pero, en cambio, JS detecta el primer evento keydown, lo retrasa por un segundo y luego detecta el resto.
Algo así:
keydown> "f" key detected... (1 second delay) "f" key detected... "f" key detected... "f" key detected... "f" key detected... "f" key detected...Asumo que ya entiendes mi punto.
¿Cómo puedo detectar siempre eventos keydown sin demora?
Tenga en cuenta que estoy usando el habitual document.addEventListener("keydown", ...) para ello.
Avance
https://i.imgur.com/ro1HZWQ.mp4
Editar: algunos de ustedes han estado pidiendo código.
document.addEventListener("keydown", (e) => { if (e.key == "f") { fire(1); // Since "!e.repeat" is not included, it will fire 1 round every time the key event is detected, and stop when the key goes up. } });Comportamiento esperado:
keydown> "f" key detected... "f" key detected... "f" key detected... "f" key detected... "f" key detected... "f" key detected...Comportamiento real:
keydown> "f" key detected... (1 second delay) "f" key detected... "f" key detected... "f" key detected... "f" key detected... "f" key detected...Supongo que está disparando en cada evento keydown , mientras que en realidad debería cambiar una variable isFiring a "on/true" en keydown , y cambiarla a "off/false" en keyup :
const conDiv = document.getElementById('continuous'); const onDiv = document.getElementById('onKeyDown'); let isFiring = false; let isFiringShots = 0; let onKeyDownShots = 0; function render() { conDiv.innerHTML = `Shots using "isFiring" variable fired: ${isFiringShots}`; onDiv.innerHTML = `Shots using "keydown" fired: ${onKeyDownShots}`; } setInterval(() => { render(); if (isFiring) { isFiringShots += 1; } }, 50); document.addEventListener('keydown', (e) => { if (e.keyCode == 74) { onKeyDownShots += 1; isFiring = true; } }); document.addEventListener('keyup', (e) => { if (e.keyCode == 74) { isFiring = false; } }); <h2>Click here and press "j"</h2> <div id="continuous">Shots using `isFiring` variable fired: 0</div> <div id="onKeyDown">Shots using `keydown` fired: 0</div>