SpriteKit与2个非动态实体发生了关联问题

时间:2014-06-17 11:06:00

标签: ios7 sprite-kit

我正在尝试使用可以移动的块创建一个游戏,它们都属于同一个类别.BitMask。除非我将physicsBody设置为动态,否则didBeginContact不会触发。如何检测属于同一类别的两个块之间的冲突?

生成块的代码:

float blkX = 34;
    float blkY = 64;

    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 6; j++){
            block = [SKSpriteNode spriteNodeWithImageNamed:blocksArray[(arc4random()%5)]];
            block.position = CGPointMake(blkX, blkY);
            block.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:block.size];
            block.physicsBody.usesPreciseCollisionDetection = YES;
            block.physicsBody.dynamic = NO;
            block.physicsBody.categoryBitMask = blockCategory;
            block.physicsBody.contactTestBitMask = blockCategory;
            block.physicsBody.collisionBitMask =  blockCategory;
            [block setName:@"block"];
            [_bgLayer addChild:block];
            blkX += 48;
        }
        blkX = 34;
        blkY += 48;
    }

我正在使用SKPhysicsContactDelegate并在我的init方法中包含以下两行:

self.physicsWorld.contactDelegate = self;
self.physicsWorld.gravity = CGVectorMake(0.0, 0.0);

我的didBeginContact方法:

-(void)didBeginContact:(SKPhysicsContact *)contact{
SKPhysicsBody *firstBody, *secondBody;

firstBody = contact.bodyA;
secondBody = contact.bodyB;

NSLog(@"We Collided!");

}

任何帮助表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:1)

我确实想出了一些适用于类似情况的人:

在我的touchesBegan方法中,我将被移动的块设置为Dynamic,它会触发didBeginContact。这是我的touchesBegan方法:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self.selectedNode = [self nodeAtPoint:[[touches anyObject] locationInNode:self]];
    [self.selectedNode.physicsBody setDynamic:YES];
}

然后在touchesEnded方法中再次关闭它。

我还设置了允许块移动到其他块的block.physicsBody.collisionBitMask = 0。如果这对至少另一个人有帮助,则值得提出问题!