如何测试 SKNode 子类中的 SK 物理接触?

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

我有一个名为 Cell 的 SKNode 子类。我设置了所有的物理体,它们正确地碰撞了。但是,didBeginContact() 函数在 GameScene 中,我需要它在 Cell 中,因为我想调用在单元格中声明的函数来更改单元格属性。有没有办法将委托设置为 SKNode 子类?或者我可以变通并从 GameScene 调用 Cell 中的函数吗?

设置位掩码:

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

在 Cell 内部,设置物理体:

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

另请注意:我使用的是 Swift 3.0

编辑:下面的答案是正确的。提醒大家:

func didBeginContact(contact: SKPhysicsContact) {
    ...
}

已重命名为

func didBegin(_ contact: SKPhysicsContact) {
    ...
}

截至 Swift 3.0

将您的 didBeginContact 保持在原处(或者至少不要将其移至 Cell)。你想要的是将节点投射到你的 class Cell,它的要点是这样的:

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

上面的内容会比较混乱,肯定应该重构,但它应该可以帮助你继续前进....

也许更干净一些:

let cell: Cell? = contactBodyA.node as? Cell ?? contactBodyB.node as? Cell
cell?.someFunction()