所以我的问题是球刚刚穿过砖块,没有任何反应。我将整个代码放在jsbin中,这里我只发布不起作用的那个。如你所见,我有一个弹跳球,球拍,砖块和动画框架功能。
for (var i in bricks) {
if (!bricks[i].isDestroyed) {
if (
(this.y + this.radius == bricks[i].y - bricks[i].height)
&& (this.x >= bricks[i].x)
&& (this.x <= bricks[i].x + bricks[i].width)
) {
bricks[i].isDestroyed = true;
destroyedBrick = true;
this.direction.y = "up";
ctx.clearRect(bricks[i].x, bricks[i].y, bricks[i].width, bricks[i].height);
}
if (
(this.y - this.radius == bricks[i].y)
&& (this.x >= bricks[i].x)
&& (this.x <= bricks[i].x + bricks[i].width)
) {
bricks[i].isDestroyed = true;
destroyedBrick = true;
this.direction.y = "down";
ctx.clearRect(bricks[i].x, bricks[i].y, bricks[i].width, bricks[i].height);
}
if (
(this.x - this.radius == bricks[i].x)
&& (this.y - this.radius <= bricks[i].y)
&& (this.y - this.radius >= bricks[i].y - bricks[i].height)
) {
bricks[i].isDestroyed = true;
destroyedBrick = true;
this.direction.x = "left";
ctx.clearRect(bricks[i].x, bricks[i].y, bricks[i].width, bricks[i].height);
}
if (
(this.x == bricks[i].x + bricks[i].width)
&& (this.y - this.radius <= bricks[i].y)
&& (this.y - this.radius >= bricks[i].y - bricks[i].height)
) {
bricks[i].isDestroyed = true;
destroyedBrick = true;
this.direction.x = "right";
ctx.clearRect(bricks[i].x, bricks[i].y, bricks[i].width, bricks[i].height);
}
}
}
答案 0 :(得分:1)
当您可能需要不等式时,看起来碰撞代码在某些检查中使用==。所以我的猜测是球越过那个确切的位置,导致其他检查被跳过。根据需要将所有比较切换为&gt; =或&lt; =并查看是否修复了它。
答案 1 :(得分:1)
修正了你的代码。
基本上,我将==
更改为<=
,因为球永远不会打到这个精确的位置。此外,我在每个break
条件中添加了if
,以便在一块砖被击中时退出检查,因为您希望球跳下而不是消灭整排。
for (var i in bricks) {
if (!bricks[i].isDestroyed) {
if ((this.y + this.radius <= bricks[i].y - bricks[i].height) && (this.x >= bricks[i].x) && (this.x <= bricks[i].x + bricks[i].width)) {
bricks[i].isDestroyed = true;
destroyedBrick = true;
this.direction.y = "up";
ctx.clearRect(bricks[i].x, bricks[i].y, bricks[i].width, bricks[i].height);
break;
}
if ((this.y - this.radius <= bricks[i].y) && (this.x >= bricks[i].x) && (this.x <= bricks[i].x + bricks[i].width)) {
bricks[i].isDestroyed = true;
destroyedBrick = true;
this.direction.y = "down";
ctx.clearRect(bricks[i].x, bricks[i].y, bricks[i].width, bricks[i].height);
break;
}
if ((this.x - this.radius <= bricks[i].x) && (this.y - this.radius <= bricks[i].y) && (this.y - this.radius >= bricks[i].y - bricks[i].height)) {
bricks[i].isDestroyed = true;
destroyedBrick = true;
this.direction.x = "left";
ctx.clearRect(bricks[i].x, bricks[i].y, bricks[i].width, bricks[i].height);
break;
}
if ((this.x <= bricks[i].x + bricks[i].width) && (this.y - this.radius <= bricks[i].y) && (this.y - this.radius >= bricks[i].y - bricks[i].height)) {
bricks[i].isDestroyed = true;
destroyedBrick = true;
this.direction.x = "right";
ctx.clearRect(bricks[i].x, bricks[i].y, bricks[i].width, bricks[i].height);
break;
}
}
}
修改强>
当你的球撞到“内砖”时,你会出现问题,比如在一排上方还有砖块的砖块。因为你的球将根据你当前的条件消灭这些砖块,因为球的坐标将小于砖块的坐标。但这更像是你逻辑的一般问题。您需要为此包含更多检查。 ;)