好的 我是编码新手,尝试制作一个小乒乓球克隆。 不知怎的,当这个对象到达 Canvas 元素的底部时,它就消失了。
这是我的代码:
var padle = {
x: 0,
y: 150,
w: 20,
h: 50,
// Add vx and vy properties here:
vx: 0,
vy: 100,
ax: 0,
ay: 0,
color: "#FAFAFA",
draw: function() {
ctx.beginPath();
ctx.fillRect(this.x, this.y, this.w, this.h );
ctx.fillStyle = this.color;
ctx.fill();
},
update: function() {
// Update the particle's position
this.vx += this.ax / FPS;
this.vy += this.ay / FPS;
this.x += this.vx / FPS;
this.y += this.vy / FPS;
if ( this.x < 0 ) {
this.x = 0;
this.vx = -this.vx;
}
if ( this.x > canvas.width ) {
this.x = canvas.width;
this.vx = -this.vx;
}
if (this.y < 0 ) {
this.y = 0;
this.vy = -this.vy;
}
if ( (this.y + this.h)> canvas.height ) {
this.y = canvas.height;
this.vy = -this.vy;
}
}
};`
怎么了?实在是没看懂。
最佳答案
你的陈述
if ( (this.y + this.h)> canvas.height ) {
this.y = canvas.height;
this.vy = -this.vy;
}
将 this.y
设置为 canvas.height
,而实际上应该将其设置为 canvas.height - this.h
。发生的情况是,您告诉该项目“如果您的底部边缘位于 Canvas 下方,则将您的顶部边缘设置为恰好位于 Canvas 的底部”,并导致此代码在循环中每次都进行计算,即为什么它似乎“消失”了。它卡在 Canvas 底部下方。
关于javascript - 为什么这个物体会消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20641682/