5

I don't think there is a way to do this, but is there a way to detect when 2 SKSpriteNodes intersect with each other, but still allow them to overlap, so they don't actually bounce over each other?

I know I can just have 1 without a physics body, and then write some code to check their co-ordinates, but I thought maybe I might be missing something in Sprite Kit where I could detect this with SK methods.

godel9
  • 7,340
  • 1
  • 33
  • 53
Cocorico
  • 2,319
  • 3
  • 22
  • 31

1 Answers1

10

You can use the contactDelegate property of the SKPhysicsWorld object:

// 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
}

You'll also need to declare your SKScene sub-class as implementing the SKPhysicsContactDelegate protocol.

Here's more reference info:

Simon Degn
  • 901
  • 1
  • 12
  • 40
godel9
  • 7,340
  • 1
  • 33
  • 53
  • Yes, this is fine, but I was trying to detect contact between 1 body WITH a physics body and one without, which I don't think this allows for, don't you have to connect the contactTestBitMask to a physics body? – Cocorico Dec 08 '13 at 17:12
  • Yes, you need a physics body, but you can just set the body's `dynamic` to `NO` and `collisionBitMask` to `0x00000000`, and it won't interact with anything. – godel9 Dec 08 '13 at 17:14
  • You have no idea how long I was searching for such a clear answer! Thanks! – Terrabythia Dec 21 '13 at 15:17
  • Wow I totally didn't know about that ~category thingy. Thanks dude. – GeneCode Jan 29 '17 at 07:57