javascript - 为什么这个物体会消失?

标签 javascript html canvas

好的 我是编码新手,尝试制作一个小乒乓球克隆。 不知怎的,当这个对象到达 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/

相关文章:

javascript - 出错时显示div

javascript - 按钮在 "Uncaught SyntaxError: Unexpected token ("中创建 "<DOCTYPE html>"

html - 如何使用 bootstrap 和 css 使元素响应?

javascript - 我想每次点击 requestFrameAnimation 时都开始一个新的动画

javascript - 我在 Canvas 中的自定义工具提示必须显示一次而不是循环显示

css - 将 svg 转换为 png 时如何包含 CSS 样式

javascript - 我需要这些手工制作的组件吗(将通过 props 和条件包装器的 React.Fragment)

javascript - 如何在javascript中将字符串的每个单词的第一个字符大写?

javascript - 如何改变网页上文本框的大小?

javascript - 最快的高斯模糊不起作用