Reputation: 33
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();
Upvotes: 3
Views: 44
Reputation: 1542
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
Upvotes: 1