2016-09-19 90 views
1

使用Cocos2d-JS创建一个小突破克隆时,我设法通过否定(或乘以 - 1)X或Y值。检测一个物体与多个物体相撞/否定多个物体的次数

这个工作,至少直到球(它实际上是一个精灵的小矩)一次击中两个方块,此时X或Y值被否定两次。

然后球继续其路径没有弹跳,导致一个非常短暂和非常奇怪的突围比赛。

有没有什么方法可以检测出有多少物品与球碰撞,并且无视其中一个?

或者还有其他方法可以做到这一点吗?

谢谢。

这里是我的代码冲突:

if (Tools.rectsIntersect(this, g_Ball)) { 
     if (g_Ball.y < this.y || g_Ball.y > this.y) { 
      g_Ball.yDirection = g_Ball.yDirection * -1; 
     } 
     else if (g_Ball.x < this.x || g_Ball.x > this.x) { 
      g_Ball.xDirection = g_Ball.xDirection * -1; 
     } 
     this.destroyBlock(); 
} 


Tools.rectsIntersect = function (obj1, obj2) {box 
    var aRect = obj1.collideRect(); 
    var bRect = obj2.collideRect(); 
    return cc.rectIntersectsRect(aRect, bRect); 
}; 

回答

1

不知道你是如何启动该碰撞检查(我假设你还是发动机罩下使用requestAnimationFrame,或setInterval的,然后你只是迭代在每一块砖上进行测试并对球进行测试),很难给你一个完美的解决方案。但假设你正在做的是这样的事情,那还剩下一个设计问题。球应该能够同时击中2个方块吗?

// if YES: 
var allTheBlocks = someListOfAllTheBlocks; 
var reflectInX = false; 
var reflectInY = false; 

for (var i = 0; i < allTheBlocks.length; i++) { 
    var thisBlock = allTheBlocks[i]; 
    if (Tools.rectsIntersect(thisBlock, g_Ball)) { 
     if (g_Ball.y < thisBlock.y || g_Ball.y > thisBlock.y) { 
      reflectInY = true; 
     } else if (g_Ball.x < thisBlock.x || g_Ball.x > thisBlock.x) { 
      reflectInX = true; 
     } 
     thisBlock.destroyBlock(); 
    } 
} 

if (reflectInY) { 
    g_Ball.yDirection *= -1; 
} 

if (reflectInX) { 
    g_Ball.xDirection *= -1; 
} 

//===================== 
// OR, if NO: 
var allTheBlocks = someListOfAllTheBlocks; 

for (var i = 0; i < allTheBlocks.length; i++) { 
    var thisBlock = allTheBlocks[i]; 
    if (Tools.rectsIntersect(thisBlock, g_Ball)) { 
     if (g_Ball.y < thisBlock.y || g_Ball.y > thisBlock.y) { 
      g_Ball.yDirection *= -1; 
     } else if (g_Ball.x < thisBlock.x || g_Ball.x > thisBlock.x) { 
      g_Ball.xDirection *= -1; 
     } 
     thisBlock.destroyBlock(); 
     break; 
    } 
} 
// And then if the ball has traversed too far in that frame, due to lag, or loose math, 
// make sure to manually set it's position to be outside of the block it hit. Or if you are 
// playing that your ball has some 'flex' to it, then just leave it be. 

有明显的优化可以在碰撞加位置代码中完成,但是有什么可以完成的。

+0

我用cocos2D内建的cc.rectIntersectsRect函数。我不完全确定它是如何工作的,但是你有正确的想法将块放入一个数组中。虽然在碰撞事故中我遇到了麻烦,但有时候方向不会颠倒,尽管在我最初的代码中,到目前为止,他们都有了相反的方向。 –