Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying prototype functions to 2 different objects in a loop only works on the second object

Tags:

javascript

Sorry if question is bad. Its my first one. Im setting prototype functions on Ball object instances but in the loop the function only work on the instance that is called second(last). I tries to search for answer online.

function Ball(x, y, velX, velY, color, size) {
    this.x = x;
    this.y = y;
    this.velX = velX;
    this.velY = velY;
    this.color = color;
    this.size = size;
}

Ball.prototype.draw = function() {
    ctx.beginPath();
    ctx.fillStyle = this.color;
    ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
    ctx.fill();
}

Ball.prototype.boundaries = function() {
    if (this.x - this.size > width) {
        this.x = 0 - this.size;
    } else if (this.x + this.size < 0) {
        this.x = width - this.size;
    } else if (this.y - this.size > height) {
         this.y = 0 - this.size;
    } else if (this.y + this.size < 0) {
        this.y = height - this.size;
    }
}

/** Controls that is only working on second object**/
Ball.prototype.setControls = function() {
    let _this = this;
    window.onkeydown = function(e) {
        if (e.key === 'a' && _this.velX > -4) {
            _this.velX -= 1;
        } else if (e.key === 'd' && _this.velX < 4) {
            _this.velX += 1;
        } else if (e.key === 'w' && _this.velY > -4) {
            _this.velY -= 1;
        } else if (e.key === 's' && _this.velY < 4) {
            _this.velY += 1;
        }
    }

   this.x += _this.velX;
   this.y += _this.velY;
}


let testBall = new Ball(50, 100, 4, 4, 'blue', 10);
let ball2 = new Ball(200, 200, 4, 4, 'green', 12);

function loop() {
    ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';
    ctx.fillRect(0, 0, width, height);


    /** If I switch testBall with ball2** setControls 
    will work on testBall**/
    testBall.draw();
    testBall.setControls();
    testBall.boundaries();

    ball2.draw();
    ball2.boundaries();
    ball2.setControls();

I've tried to put an if else statement where I initialize x = 1 before the loop and the for each odd num I run the function on 1 object and then even numbers on the other object but its laggy and it obviously becomes a problem when I need more objects.

    requestAnimationFrame(loop);
}

loop();
like image 515
Renier Vermeulen Avatar asked Dec 06 '25 08:12

Renier Vermeulen


1 Answers

by using window.onkeydown = you are overriding the existing handler, so it will work only for the last initialized instance, you can use addEventListener instead

like image 66
Zac Avatar answered Dec 08 '25 20:12

Zac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!