我正在开发一个SpriteKit项目。我通过node.physicsBody?.joints。
访问我的节点的关节它应该包含一个SKPhysicsJointPin,实际上我得到一个包含一个SKPhysicsJoint对象的数组。
但是我无法将它从SKPhysicsJoint转发到SKPhysicsJointPin
for joint in (node.physicsBody?.joints)! {
print("Joint found") // Is executed
if let myJoint = joint as? SKPhysicsJointPin {
print("SKPhysicsJointPin object found") // Is not executed
}
}
我创建的关节当然是SKPhysicsJointPin对象,但我的程序没有执行第二个print语句。
为什么不能贬低它呢?我偶然发现了一个错误吗?
由于
答案 0 :(得分:0)
是的。 +[SKPhysicsJointPin allocWithZone:]
会返回PKPhysicsJointRevolute
:
+[SKPhysicsJointPin allocWithZone:]:
000b8bd4 push ebp ; Objective C Implementation defined at 0x1817fc (class)
000b8bd5 mov ebp, esp
000b8bd7 sub esp, 0x18
000b8bda call 0xb8bdf
000b8bdf pop eax ; XREF=+[SKPhysicsJointPin allocWithZone:]+6
000b8be0 mov ecx, dword [ss:ebp+arg_8]
000b8be3 mov edx, dword [ds:eax-0xb8bdf+objc_cls_ref_PKPhysicsJointRevolute] ; objc_cls_ref_PKPhysicsJointRevolute
000b8be9 mov eax, dword [ds:eax-0xb8bdf+0x16e5b0] ; @selector(allocWithZone:)
000b8bef mov dword [ss:esp+0x18+var_10], ecx
000b8bf3 mov dword [ss:esp+0x18+var_14], eax ; argument "selector" for method imp___symbol_stub__objc_msgSend
000b8bf7 mov dword [ss:esp+0x18+var_18], edx ; argument "instance" for method imp___symbol_stub__objc_msgSend
000b8bfa call imp___symbol_stub__objc_msgSend
000b8bff add esp, 0x18
000b8c02 pop ebp
000b8c03 ret
; endp
这是来自PhysicsKit的一个类(私有框架)。在ObjC中无关紧要,因为类型是我们所说的,只要对象响应正确的选择器。在Swift中,这会产生类型不匹配,因为类型不仅仅是我们所说的。
您可能会在ObjC中创建一个桥梁以使其工作,但您可能会遇到“使用私有框架”问题。这座桥看起来像这样(未经测试):
// Trust me, compiler, this class will exist at runtime
@class PKPhysicsJoinRevolute;
// And hey, here are some methods that I also promise will exist.
@interface PKPhysicsJointRevolute (Bridge)
@property(nonatomic) CGFloat rotationSpeed;
// ... whatever properties you need ...
@end
但就像我说的那样,这可能会让你陷入困境。所以相反,你可能想制作一个类似(未经测试的)
的ObjC包装器@interface MYPinWrapper : NSObject
@property (nonatomic, readonly, strong) SKPhysicsJointPin *pin;
- (instancetype)initWithPin:(id)pin;
@end
@implementation MYPinWrapper {
- (instancetype)initWithPin:(id)pin {
_pin = (SKPhysicsJointPin *)pin;
}
@end
然后你的Swift看起来像:
for joint in (node.physicsBody?.joints)! {
print("Joint found") // Is executed
let pin = MYPinWrapper(pin: joint).pin // Launder the pin through ObjC
// ... pin should now work like a pin even though it's really a revolute.
}