mazen
mazen

Reputation: 63

collisions in swift and spritekit

I'm working with a simple game using Swift and Spritekit .

I have 4 nodes in my scene : nodeA1 , nodeA2 , nodeB1 and nodeB2 .

So nodeA1 can touch nodeA2 And nodeB1 can touch nodeB2 .

I want

nodeA2 touch nodeB2 without nodeA1 touch nodeB1 and nodeB2 and nodeB1 is the same.

Is that possible ?

Upvotes: 0

Views: 55

Answers (1)

Steve Ives
Steve Ives

Reputation: 8134

Yes, it is definitely possible, whether or not you mean collisions or contacts 😀

If you can clarify this, I'll tell you how to do it. (I could tell you for both, but that would be extra code.)

EDIT - code here for collisions as described:

  1. Define unique categories, ensure your class is a SKPhysicsContactDelegate and make yourself the physics contact delegate:

    //Physics categories let nodeA1Category: UInt32 = 1 << 0 // b'00001' let nodeA2Category: UInt32 = 1 << 1 // b'00010' let nodeB1Category: UInt32 = 1 << 2 // b'00100' let nodeB2Category: UInt32 = 1 << 3 // b'01000'

    class GameScene: SKScene, SKPhysicsContactDelegate { physicsWorld.contactDelegate = self

  2. Assign the categories (usually in didMove(to view:) :

    nodeA1.physicsBody.catgeoryBitMask = nodeA1Category nodeA2.physicsBody.catgeoryBitMask = nodeA2Category nodeB1.physicsBody.catgeoryBitMask = nodeB1Category nodeB2.physicsBody.catgeoryBitMask = nodeB2Category

(Make sure you've created physics bodies for each node with the isDynamic property set to true)

  1. Set up collisions:

    nodeA1.physicsBody?.collisionBitMask = nodeA2Category // A1 collides with A2 nodeA2.physicsBody?.collisionBitMask = nodeA1Category // A2 collides with A1

    nodeB1.physicsBody?.collisionBitMask = nodeB2Category // B1 collides with B2 nodeB2.physicsBody?.collisionBitMask = nodeB1Category // B2 collides with B1

    nodeA2.physicsBody?.collisionBitMask = nodeB2Category // A2 collides with B2 nodeB2.physicsBody?.collisionBitMask = nodeA2Category // B2 collides with A2

You should now get all the collisions you want, but no contact notifications. If you want to do something the these nodes collide, you'll have to implement contactTest bit masks and also the didBeg(contact:) method.

Upvotes: 1

Related Questions