ios - SKPhysicsContact 崩溃的扩展

标签 ios swift sprite-kit crash skphysicscontact

我正在使用 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/

相关文章:

ios - 为什么我的 UINavigtionController 栏只有在我覆盖它时才会在 iOS 7 上错误定位?

swift - 如何检查 2 张图像是否相互匹配 - Swift Apple Watch

ios - 为什么 UICollectionView cellForItemat indexpath 会在一开始就为所有单元格调用

ios - SpriteKit 和可滚动列表

ios - 如何开启Cocos2D CCLOG Debug模式?

ios - iPhone 6 模拟器中的 LaunchScreen 与实体 iPhone 6 不同

ios - Firebase addStateDidChangeListener

ios - 重新定义 SKNode 意味着我必须将节点重新添加为子节点?

ios - 有效检测碰撞

ios - iPhone 6 Plus 分辨率困惑 : Xcode or Apple's website? 用于开发