Reputation: 31
// 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?
Upvotes: 0
Views: 45
Reputation: 514
By using window.onkeydown
, you're overriding all other keydown
event listeners on the window
object. 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.
Upvotes: 1