SpriteKit碰撞检测

时间:2014-04-15 19:40:05

标签: ios objective-c collision-detection sprite-kit

试图让一个固定的炮塔射向一个移动的敌人(塔防游戏)。

static const uint32_t towerCategory  = 0x1 << 0;
static const uint32_t creepCategory  = 0x1 << 1;

如果上述说法正确,那么towerCategory应该具有较低的类别编号吗?

tower.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:80];
tower.physicsBody.dynamic = YES;

tower.physicsBody.categoryBitMask = towerCategory;
tower.physicsBody.contactTestBitMask = creepCategory;
tower.physicsBody.collisionBitMask = 0;

这应该将塔节点设置在towerCategory中,并对蠕变移动到范围(范围是80半径物理体)之间的接触作出反应。由于我也不希望塔或蠕变相互推动,我将碰撞设置为0。

baddie.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:baddie.size];
baddie.physicsBody.dynamic = YES;

baddie.physicsBody.categoryBitMask = creepCategory;
baddie.physicsBody.contactTestBitMask = towerCategory;
baddie.physicsBody.collisionBitMask = 0;

对敌人来说也是如此。我切换类别并联系bitMask,因为这个应该是一个蠕变,它接触塔。仍然没有碰撞,所以将它设置为0。

    SKPhysicsBody* firstBody;
    SKPhysicsBody* secondBody;

if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
{
    firstBody = contact.bodyA;
    secondBody = contact.bodyB;
}
else
{
    firstBody = contact.bodyB;
    secondBody = contact.bodyA;
}

    if ((firstBody.categoryBitMask & towerCategory) != 0 &&
        (secondBody.categoryBitMask & creepCategory) != 0)
    {
        [secondBody.node removeAllActions];
    }

我很确定didBeginContact函数是失败的地方。由于towerCategory低于creepCategory,如果我的代码正确,它应该总是放在firstBody中。然后当蠕变进入接触范围时,它应该从中移除所有动作并停在轨道上。然而,他只是不断前进。有人可以指出我缺少的东西吗?

1 个答案:

答案 0 :(得分:1)

didBeginContact:

试用此代码
- (void)didBeginContact:(SKPhysicsContact *)contact
{
    NSLog(@"bodyA:%@ bodyB:%@",contact.bodyA.node.name, contact.bodyB.node.name); // <- this gives you who touched who by object name

    uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);

    if (collision == (towerCategory | creepCategory))
    {
        NSLog(@"we got contact...");
    }
}

请记住,contact.bodyA.node.(property)可以为您提供SKNode的任何属性。名称,位置,xScale,yScale,alpha,children,parent等等。您可以在SKNode Class Reference列出所有内容。