Michael Austin Michael Austin - 1 year ago 58
Swift Question

How can I test for a SK physics contact within a SKNode subclass?

I have a subclass of SKNode called

. I set up all the physics bodies and they collide properly. However, the
function is in
and I need it to be in
because I want to call a function declared in cell that alters the cells properties. Is there a way to set the delegate to an SKNode subclass? Or can I workaround and call the function within Cell from GameScene?

set up bit mask:

let cellCategory: UInt32 = 0x1 << 0
let foodCategory: UInt32 = 0x1 << 1
let borderCategory: UInt32 = 0x1 << 2

inside Cell, setup the physics body:

let physicsBody = SKPhysicsBody(circleOfRadius: 5)
self.physicsBody = physicsBody
self.physicsBody!.affectedByGravity = false
self.physicsBody!.allowsRotation = false
self.physicsBody!.categoryBitMask = cellCategory
self.name = "cell"
self.physicsBody!.contactTestBitMask = cellCategory | borderCategory

also note: I am using Swift 3.0

EDIT: The answer below is correct. Heads-up to everyone:

func didBeginContact(contact: SKPhysicsContact) {

has been renamed to

func didBegin(_ contact: SKPhysicsContact) {

as of Swift 3.0

Answer Source

Keep your didBeginContact where it is (or at least don't move it to Cell). What you want is to cast to the node to your class Cell, the gist of it would something like this:

func didBeginContact(contact: SKPhysicsContact) {
    if let cell = contact.bodyA.node as? Cell {
    } else if let cell = contact.bodyB as? Cell {

The above will be rather messy and should be refactored for sure, but it should help you to get on the way....

Somewhat cleaner perhaps:

let cell: Cell? = contactBodyA.node as? Cell ?? contactBodyB.node as? Cell