SKPhysicsBody 的 Swift 便利初始化程序扩展

2024-01-13

extension SKPhysicsBody {

    /// anchorPoint version of init(rectangleOfSize:center:)
    convenience init(rectangleOfSize s: CGSize, withAnchorPoint anchorPoint: CGPoint) {
        var center = CGPoint()
        center.x = (s.width / 2) - ( s.width * anchorPoint.x)
        center.y = (s.height / 2 ) - ( s.height * anchorPoint.y)
        self.init(rectangleOfSize: s, center: center)
    }

}

我在运行时收到此错误

-[PKPhysicsBody initWithRectangleOfSize:withAnchorPoint:]: unrecognized selector sent to instance 0x7f9b03c4fff0

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[PKPhysicsBody initWithRectangleOfSize:withAnchorPoint:]: unrecognized selector sent to instance 0x7f9b03c4fff0'

这就是我在代码中调用的方式

// redBox is a typical SKSpriteNode()
redBox.physicsBody = SKPhysicsBody(rectangleOfSize: redBox.frame.size, withAnchorPoint: redBox.anchorPoint)

我基本上想延长SKPhysicsBody类为其工厂方法提供方便的初始值设定项


正如 @Cristik 在评论中猜测的那样,这与以下问题的根本问题相同:这个问题 https://stackoverflow.com/q/28501832/957768 and 这个问题 https://stackoverflow.com/q/25004232/957768: 公众SKPhysicsBody类是私有的便捷接口PKPhysicsBody提供其实现的类。

过去,这种方法很大程度上依赖于“鸭子打字” https://en.wikipedia.org/wiki/Duck_typingObjective-C 的行为——只要ClassA响应所有相同的选择器ClassB,您可以在其静态类型(在源代码中向编译器声明的类型)为的指针上调用任何这些选择器ClassB,即使运行时的实际对象实际上是ClassA.

Swift 对运行时类型正确性的要求比 ObjC 更严格,因此仅“鸭子类型”是不够的。自 iOS 9 / OS X 10.11 起,SpriteKit 有一些解决方法,允许PKPhysicsBody更好地假装的实例SKPhysicsBody实例。

但这些并不能涵盖所有情况——特别是,它没有抓住(ObjC)[SKPhysicsBody alloc]返回一个PKPhysicsBody实例,这意味着任何尝试添加初始化程序SKPhysicsBody在 Swift 中会失败。 (因为 ObjCalloc/init在 Swift 中,这一过程被简化为一个初始化程序调用。)

我认为这是一个错误并推荐向 Apple 提交 http://bugreport.apple.com.


编辑/更新:在该错误得到修复之前(现在已经过去一年多了),解决方法是将您的方便“初始化程序”改为类方法。 (或者如果必须的话,可以使用全局函数,但是...... ewww。)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SKPhysicsBody 的 Swift 便利初始化程序扩展 的相关文章

随机推荐