Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
Don't work controls to play for two players
// methods for key
 setControlsButton(){
    var _this = this;
    window.onkeydown = function(e) {
        if (e.keyCode === 65) {
            _this.x -= _this.velX;
            } else if (e.keyCode === 68) {
            _this.x += _this.velX;
            } else if (e.keyCode === 87) {
            _this.y -= _this.velY;
            } else if (e.keyCode === 83) {
            _this.y += _this.velY;
        }
    }
}

setControlsArrow(){
    var _this = this;
    window.onkeydown = function(e) {
        if (e.keyCode === 37) {
            _this.x -= _this.velX;
            } else if (e.keyCode === 39) {
            _this.x += _this.velX;
            } else if (e.keyCode === 38d) {
            _this.y -= _this.velY;
            } else if (e.keyCode === 40) {
            _this.y += _this.velY;
        }
    }
}

method call

player1.draw();
player1.checkBounds();
player1.collisionDetect();
player1.setControlsButton();

player2.draw();
player2.checkBounds();
player2.collisionDetect();
player2.setControlsArrow();
// code

I want to control two players: arrow keys and 'wasd'. But only the last called method works, i.e. setControlsArrow(). Please help, how to make controls for two player in vanila js?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

By using window.onkeydown, you're overriding all other keydown event listeners on the windowobject. So when you call the second method, you delete the listener you set on the first one.

You should use window.addEventListener('keydown', function(e){...}); instead.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda