我正在做一个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语句。
为什么不能向下转换到它?我是不是被虫子绊倒了?
谢谢
发布于 2016-04-26 00:11:02
是啊。+[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.
}https://stackoverflow.com/questions/36841221
复制相似问题