我有一个扩展的辅助方法SKPhysicsContact
extension SKPhysicsContact {
/// - returns: `[SKPhysicsBody]` containing all the bodies that match `mask`
func bodiesMatchingCategory(mask: UInt32) -> [SKPhysicsBody] {
let bodies = [bodyA, bodyB]
return bodies.filter { ($0.categoryBitMask & mask) != 0 }
}
}
在didBeginContact()
我对传入的contact
.
func didBeginContact(contact: SKPhysicsContact) {
let ballMask: UInt32 = 0x1 << 2
let ball = contact.bodiesMatchingCategory(ballMask)
...
我有时会收到此错误消息(如五分之一),这会使应用程序崩溃:
-[PKPhysicsContact bodiesMatchingCategory:]: unrecognized selector sent to instance 0x165f2350
我查了一下PKPhysicsContact
,它是私有框架(链接)的一部分。 SKPhysicsContact
看起来它只是一个空的类定义,它只公开PKPhysicsContact
.
我觉得这是 SpriteKit 团队的一个 Objective-C hack,它打破了 Swift 的强类型。
帮助?
如何确保我总是SKPhysicsContact
回来?
我添加了一个检查来测试SKPhysicsContact
let test = contact as Any
print("Test is: \(test)")
guard test is SKPhysicsContact else {
return
}
哪个正确捕获了类型不匹配。
事实上,它从不返回SKPhysicsContact
!!?
我已经尝试在 Objective-C 中执行此操作(如响应者所建议的那样),我得到了相同的结果。
我在Apple Dev Forums上进行了讨论,这可能会为未来的答案寻求者提供一些帮助。
这是供参考的Objective-C代码:
@interface SKPhysicsContact (MatchingBodies)
- (NSArray *)bodiesMatchingCategory:(UInt32)category;
@end
@implementation SKPhysicsContact (MatchingBodies)
- (NSArray *)bodiesMatchingCategory:(UInt32)category {
NSArray *bodies = @[self.bodyA, self.bodyB];
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(SKPhysicsBody *body, NSDictionary *bindings) {
return (body.categoryBitMask & category) != 0;
}];
NSArray *matching = [bodies filteredArrayUsingPredicate:predicate];
return matching;
}
@end
在这里调用:
-(void)didBeginContact:(SKPhysicsContact *)contact
{
static const uint32_t MarbleContact = 0x1 <<1; // 2
static const uint32_t GoalContact = 0x1 <<2; // 4
SKPhysicsBody *ball = [contact bodiesMatchingCategory:MarbleContact].firstObject;
NSLog(@"Ball: %@", ball);
...
返回此崩溃:
-[PKPhysicsContact bodiesMatchingCategory:]: unrecognized selector sent to instance 0x17dad9e0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[PKPhysicsContact bodiesMatchingCategory:]: unrecognized selector sent to instance 0x17dad9e0'
为 Apple 添加了错误报告,#23332190