Cocos2D:同一类的两个对象是否发生冲突?

时间:2012-06-27 22:50:14

标签: objective-c cocos2d-iphone

处理游戏,其中板块将从上到下落下。一些板块也会在地面上“弹跳”,然后再次开始向上移动。这导致下降板与“上升板”碰撞的情况。

我的问题?我不知道如何发现这次碰撞。

由于所有的牌都来自同一个类,我无法写 if(CGRectIntersectsRect([self boundingBox], [self boudingBox])) 因为这句话永远都是真的。

我使用for循环创建板:

for(i=0; i<9; i++){

 Plate *plate = [Plate initPlate];

}

然后在整个游戏中重复使用这些牌照。

关于如何检测两个板块之间碰撞的任何想法或解决方法?任何建议都将不胜感激。

的问候。

2 个答案:

答案 0 :(得分:1)

你需要有一个管理(例如使用NSMutableArray)板块的类,而不是在Plate类上检查碰撞,而是在这个新类上进行。

假设你的数组是:

NSMuttableArray *plateSet

你可以这样做:

for (Plate *bouncingPlate in plateSet)
{
    if ([bouncingPlate bouncing])
    {
        for (Plate *fallingPlate in plateSet)
        {
            if (![fallingPlate bouncing])
            {
                /* Check for collision here between fallingPlate and bouncingPlate */
            }
        }
    }
}

或者,更优雅:

for (Plate *bouncingPlate in plateSet)
{
    if (![bouncingPlate bouncing])
    {
        continue;
    }

    for (Plate *fallingPlate in plateSet)
    {
        if ([fallingPlate bouncing])
        {
            continue;
        }
        /* Check for collision here between fallingPlate and bouncingPlate */
    }
}

答案 1 :(得分:0)

是的...您需要将它们添加到NSMutableArray,然后只需使用ccpDistance来检查碰撞

类似的东西:

for (int i=0;i<8,i++){
   for (int j=i+1,j<9,j++){
if(ccpDistance([[plates objectAtIndex:i]position],[[plates objectAtIndex:j]position])<plateRadius*2) {
//collision detected
}}}

当然,如果盘子是圆圈,这是有效的

正方形使用CGRectIntersectsRect

 for (int i=0;i<8,i++){
   for (int j=i+1,j<9,j++){
if([plates objectAtIndex:i].visible && [plates objectAtIndex:j].visible &&(CGRectIntersectsRect([[plates objectAtIndex:i]boundingBox],[[plates objectAtIndex:j]boundingBox])) {
//collision detected
}}}
相关问题