Sprite Kit - 检测联系人

时间:2014-02-13 18:10:55

标签: ios objective-c sprite-kit

我有两个Sprite节点:

-(void)createPlayer {
    SKSpriteNode *player = [SKSpriteNode node];

    player.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:enemy.size];
    player.physicsBody.categoryBitMask = playerCategory;
    player.physicsBody.contactTestBitMask = enemyCategory;

    player.position = CGPointMake(100, 160);
    player.name = @"player";
    player.zPosition = 100;

    [self addChild:player];
}

-(void)createEnemy {
    SKSpriteNode *enemy = [SKSpriteNode node];

    enemy.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:enemy.size];
    enemy.physicsBody.categoryBitMask = enemyCategory;
    enemy.physicsBody.contactTestBitMask = playerCategory;

    enemy.position = CGPointMake(300, 160);
    enemy.name = @"player";
    enemy.zPosition = 100;

    [self addChild:enemy];
}

以下MyScene.h

static const uint32_t playerCategory =  0x1 << 0;
static const uint32_t enemyCategory =  0x1 << 1;

如何检测他们是否进行了联系,以便我可以根据他们的联系方式添加操作?

1 个答案:

答案 0 :(得分:8)

您的碰撞检测需要代表方法。

MyScene.h 中,您的代码应如下所示:

@interface MyScene : SKScene <SKPhysicsContactDelegate>

MyScene.m 中将此内容添加到 initWithSize 中:

self.physicsWorld.contactDelegate = self;

现在您需要实现委托方法 didBeginContact

- (void)didBeginContact:(SKPhysicsContact *)contact {
    uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);

    if (collision == (playerCategory | enemyCategory)) {
        // Do your stuff
    }
}