我已经在这方面工作了几个星期了,我可以让它工作起来。它几乎就在那里我想我只是缺少一些东西。我基本上不能在块和球之间进行碰撞检测,就像我让他们工作一样。
球仍有机会在几秒钟内完成阻挡。我很想听到那些有类似问题的人。
这是代码;
private function checkCollision():void
{
grdx = Math.floor((ball.x) / 28);
grdy = Math.floor((ball.y) / 14);
ngrdx = Math.floor((ball.x + dx) / 28);
ngrdy = Math.floor((ball.y + dy) / 14);
if (grdy <= level.length - 1 && ngrdy <= level.length - 1 && grdy >= 0 && ngrdy >= 0)
{
if(level[grdy][ngrdx] > 0)
{
level[grdy][ngrdx] = 0;
bnm = "Block_" + grdy + "_" + ngrdx;
if (this.getChildByName(bnm) != null)
{
this.removeChild(this.getChildByName(bnm));
dx *= -1;
totalBreaks++;
trace("Hit on X");
trace("Block: " + totalBreaks + " / " + totalBlocks);
}
}
else if(level[ngrdy][grdx] > 0)
{
bnm = "Block_" + ngrdy + "_" + grdx;
level[ngrdy][grdx] = 0;
if (this.getChildByName(bnm) != null)
{
this.removeChild(this.getChildByName(bnm));
dy *= -1;
totalBreaks++;
trace("Hit on Y");
trace("Block: " + totalBreaks + " / " + totalBlocks);
}
}
if(level[ngrdy][ngrdx] > 0)
{
bnm = "Block_" + ngrdy + "_" + ngrdx;
level[ngrdy][ngrdx] = 0;
if (this.getChildByName(bnm) != null)
{
this.removeChild(this.getChildByName(bnm));
dy *= -1;
dx *= -1;
totalBreaks++;
trace("hit on X,Y");
trace("Block: " + totalBreaks + " / " + totalBlocks);
}
}
}
}
答案 0 :(得分:0)
我不确定我是否做得对,但我认为您的if else if
陈述可能存在一个问题。
在您的示例中,对checkCollision()
的调用可能会更改dx
和dy
个变量的两倍,从而导致球在击中砖块时保持同一方向。
如果我是对的,那么您可以重构您的if
语句,如下所示:
if (level[ngrdy][ngrdx] > 0)
{
[...]
}
else if (level[grdy][ngrdx] > 0)
{
[...]
}
else if (level[ngrdy][grdx] > 0)
{
[...]
}
此外,将简单测试括在括号中是一种很好的做法。所以不要写那个:
if (grdy <= level.length - 1 && ngrdy <= level.length - 1 && grdy >= 0 && ngrdy >= 0)
我会这样写:
if ((grdy <= level.length - 1) && (ngrdy <= level.length - 1) && (grdy >= 0) && (ngrdy >= 0))
从而使代码更具可读性。
干得好,继续!
编辑: 正如你的评论所说,这不是一个正确的答案,我再挖一点,我现在有另一个建议,使用一些布尔值检查是否应该在两个轴上翻转方向。我也做了一些重构:
private function checkCollision():void
{
grdx = Math.floor((ball.x) / 28);
grdy = Math.floor((ball.y) / 14);
ngrdx = Math.floor((ball.x + dx) / 28);
ngrdy = Math.floor((ball.y + dy) / 14);
var flipX:Boolean = false;
var flipY:Boolean = false;
if ((grdy <= level.length - 1) && (ngrdy <= level.length - 1) && (grdy >= 0 && ngrdy >= 0))
{
if (testBlock(grdx, ngrdy))
{
flipY = true;
}
if (testBlock(ngrdx, grdy))
{
flipX = true;
}
if (testBlock(ngrdx, ngrdy))
{
flipX = true;
flipY = true;
}
dx *= flipX ? -1 : 1;
dy *= flipY ? -1 : 1;
}
}
private function testBlock(xPos:int, yPos:int):Boolean
{
if (level[yPos][xPos] > 0)
{
trace("hit on X,Y");
level[yPos][xPos] = 0;
breakBlock("Block_" + yPos + "_" + xPos);
trace("Block: " + totalBreaks + " / " + totalBlocks);
return true;
}
return false;
}
private function breakBlock(blockName:String):void
{
if (this.getChildByName(blockName))
{
this.removeChild(this.getChildByName(blockName));
totalBreaks++;
}
}
如果碰巧是正确的解决方案,我会清除这个答案......