有没有办法检测2个SKSpriteNodes之间的碰撞,但允许它们重叠

时间:2013-12-08 00:28:28

标签: ios objective-c sprite-kit skspritenode

我认为没有办法做到这一点,但是有没有办法检测2个SKSpriteNodes何时相互交叉,但仍然允许它们重叠,所以它们实际上不会反弹彼此?

我知道我可以只有一个没有物理主体,然后编写一些代码来检查他们的坐标,但我想也许我可能会在Sprite Kit中遗漏一些东西,我可以用SK方法检测到它。

1 个答案:

答案 0 :(得分:10)

您可以使用contactDelegate对象的SKPhysicsWorld属性:

// inside your header file

typedef NS_OPTIONS(NSUInteger, CollisionCategory) {
    categoryOne = (1 << 0),
    categoryTwo = (1 << 1)
};

// inside your SKScene sub-class implementation

- (void)setupContactDelegate {
    self.physicsWorld.contactDelegate = self;

    nodeA.categoryBitMask = categoryOne;    // nodeA is category one
    nodeA.collisionBitMask = ~categoryTwo;  // nodeA does not collide w/ category two
    nodeA.contactTestBitMask = categoryTwo; // nodeA tests for contacts w/ category two

    nodeB.categoryBitMask = categoryTwo;    // nodeB is category two
    nodeB.collisionBitMask = ~categoryOne;  // nodeB does not collide w/ category one
    nodeB.contactTestBitMask = categoryOne; // nodeB tests for contacts w/ category one
}

- (void)didBeginContact:(SKPhysicsContact *)contact {
    // do whatever you need to do when the contact begins
}

- (void)didEndContact:(SKPhysicsContact *)contact {
    // do whatever you need to do when the contact ends
}

您还需要将SKScene子类声明为实施SKPhysicsContactDelegate协议。

以下是更多参考信息: