为什么这个物体会消失?

时间:2013-12-17 18:13:52

标签: javascript html5 canvas

行 我是编码的新手,并试图制作一个小pong克隆。 不知何故,当它碰到画布元素的底部时,它会消失。

这是我的代码:

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;
    }
} 
};`

怎么了?我真的不明白。

1 个答案:

答案 0 :(得分:2)

您的陈述

if ( (this.y + this.h)> canvas.height ) {
    this.y = canvas.height;
    this.vy = -this.vy;
}

this.y设置为canvas.height,当它真的应该设置为canvas.height - this.h时。发生的事情是你告诉项目“如果你的下边缘在画布下方,那么将你的上边缘设置在画布的底部”并使这段代码在你的循环中每次都要评估,这是为什么它似乎“消失”。它被卡在画布的底部以下。