Search code examples
iosobjective-csprite-kitskspritenode

Is there a way to detect collisions between 2 SKSpriteNodes but allow them to overlap


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.


Solution

  • 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: