将原型函数应用于循环中的两个不同对象,只对第二个对象有效



不好意思。这是我的第一个。我在Ball对象实例上设置原型函数,但在循环中,该函数只对第二个(最后一个)调用的实例起作用。我试着在网上寻找答案。

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();

我试着放一个if else语句,我在循环之前初始化x = 1,对于每个奇数,我在一个对象上运行函数,然后在另一个对象上运行偶数,但它的延迟,当我需要更多的对象时,它显然成为一个问题。

requestAnimationFrame(loop);
}
loop();

通过使用window.onkeydown =,您将覆盖现有的处理程序,因此它将仅适用于最后初始化的实例,您可以使用addEventListener代替

最新更新