为什么这个对象会消失

Why does this object disappear?

本文关键字:消失 对象 为什么      更新时间:2023-09-26

>OK我是编码新手,并尝试制作一个小乒乓球克隆。不知何故,当这个对象碰到画布元素的底部时,它会消失。

这是我的代码:

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 。 正在发生的事情是,您告诉项目"如果您的下边缘在画布下方,则将上边缘设置为正好在画布的底部",并导致此代码在您的循环中每次都进行评估,这就是为什么它似乎"消失"的原因。 它卡在画布底部下方。