我正在使用 SpriteKit 创建一个游戏,该游戏在 2 个物体之间发生碰撞。设置主体后,我实现了 didBegin(_contact:)
方法,如下所示:
func didBegin(_ contact: SKPhysicsContact) {
if contact.bodyA.categoryBitMask == 0 && contact.bodyB.categoryBitMask == 1 {
gameOver()
}
}
而且效果很好。
后来,在查看该方法的文档时,我发现了以下内容:
The two physics bodies described in the contact parameter are not passed in a guaranteed order.
为了安全起见,我扩展了 SKPhysicsContact
类,添加了一个函数,可以在两个主体之间交换 categoryBitMask,如下所示:
extension SKPhysicsContact {
func bodiesAreFromCategories(_ a: UInt32, and b: UInt32) -> Bool {
if self.bodyA.categoryBitMask == a && self.bodyB.categoryBitMask == b { return true }
if self.bodyA.categoryBitMask == b && self.bodyB.categoryBitMask == a { return true }
return false
}
}
问题是当函数被调用时,应用程序崩溃,我收到以下错误:
2017-07-18 13:44:18.548 iSnake Retro[17606:735367] -[PKPhysicsContact bodiesAreFromCategories:and:]: unrecognized selector sent to instance 0x60000028b950
2017-07-18 13:44:18.563 iSnake Retro[17606:735367] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[PKPhysicsContact bodiesAreFromCategories:and:]: unrecognized selector sent to instance 0x60000028b950'
最佳答案
这显然是一个错误,如此处所回答: https://stackoverflow.com/a/33423409/6593818
The problem is, the type of contact is PKPhysicsContact (as you've noticed), even when you explicitly tell it to be an SKPhysicsContact, and the extension is on SKPhysicsContact. You'd have to be able to make an extension to PKPhysicsContact for this to work. From this logic, we can say that no instance methods will work in SKPhysicsContact extensions at the moment. I'd say it's a bug with SpriteKit, and you should file a radar. Class methods still work since you call them on the class itself.
In the meantime, you should be able to move that method into your scene or another object and call it there successfully.
For the record, this is not a Swift-specific problem. If you make the same method in an Objective-C category on SKPhysicsContact you'll get the same crash.
您可以向苹果提交错误报告:
https://developer.apple.com/bug-reporting/
并将其报告给社区:
https://openradar.appspot.com/search?query=spritekit
但是,您真正想用代码做的是将类别掩码加在一起。然后检查总和(无论 bodyA 和 bodyB 的顺序如何,2 + 4 和 4 + 2 总是等于 6)。
这就是您如何获得独特的联系方式,如果您正确地设置您的掩码为 2 的幂(2、4、8、16 等)
关于ios - SKPhysicsContact 崩溃的扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45164773/