Karan Jariwala
Karan Jariwala

Reputation: 727

Set Controls not working for one object instance but works for other

I'm trying to create a Multi-player game using JS.

    function EvilBall(player,color)
{
    EvilCircle.call(this,this.size,this.velY,this.velX);
    this.color=color;
    this.score =0;
    this.player=player;

} 

EvilBall.prototype=Object.create(EvilCircle.prototype);
EvilBall.prototype.constructor =EvilBall;

   EvilBall.prototype.setControls=function(left,right,down,up){
        var _this = this;
        window.onkeydown = function(e) {
            console.log(e.keyCode);
            if (e.keyCode === left) {
                _this.x -= _this.velX;
            } else if (e.keyCode === right) {
                _this.x += _this.velX;
            } else if (e.keyCode === down) {
                _this.y -= _this.velY;
            } else if (e.keyCode === up) {
                _this.y += _this.velY;
            }
        }
    }

after this I'm creating two instances of EvilBall and setting there controls using setControls function which has event handler function inside.

var evilBall = new EvilBall('p1','white');
var evilBall2 = new EvilBall('p2','yellow');
evilBall2.setControls(65,68,87,83);
evilBall.setControls(37,39,38,40);

Only evilBall instance with key 37,39,38 and 40 is working when keys are pressed. I have figured that since evilBall is mentioned below evilBall2, it is working fine. If an event handler is working fine on one instance, why is not working on the other? How can we develop multi-player games in JS when event-handler on only one instance works? Can anyone please explain this to me. Am I missing something here?

Upvotes: 1

Views: 113

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138497

Window onkeydown is a property:

window.onkeydown = ()=>alert("one");
window.onkeydown = ()=>alert("two");//will override the first
window.onkeydown();

So use window.addEventListner instead:

window.addEventListener("keydown",function(event){
...
});

Overall it might be better to just have one event listener:

var keylisteners=[];
window.onkeydown=function(e){
 (keylisteners.find(el=>el.key==e.keyCode)||{callback:function(){}}).callback();
};

Use like this:

keylisteners.push({
 key:42,
 callback:function(){}
});

By the way, your shape function doesnt take arguments:

Shape.call(this); //will do the job too

Upvotes: 1

Related Questions