Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!