我的解决方案不需要 isKindOfClass 之类的东西......
在您的 SKScene 界面中:
@property (nonatomic, strong) SKNode* touchTargetNode;
// this will be the target node for touchesCancelled, touchesMoved, touchesEnded
在您的 SKScene 实施中
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
NSArray* nodes = [self nodesAtPoint:[touch locationInNode:self]];
self.touchTargetNode = nil;
for( SKNode* node in [nodes reverseObjectEnumerator] )
{
if( [node conformsToProtocol:@protocol(CSTouchableNode)] )
{
SKNode<CSTouchableNode>* touchable = (SKNode<CSTouchableNode>*)node;
if( touchable.wantsTouchEvents )
{
self.touchTargetNode = node;
[node touchesBegan:touches
withEvent:event];
break;
}
}
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.touchTargetNode touchesCancelled:touches
withEvent:event];
self.touchTargetNode = nil;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.touchTargetNode touchesMoved:touches
withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.touchTargetNode touchesEnded:touches
withEvent:event];
self.touchTargetNode = nil;
}
您将需要定义 CSTouchableNode 协议...随意称呼它:)
@protocol CSTouchableNode <NSObject>
- (BOOL) wantsTouchEvents;
- (void) setWantsTouchEvents:(BOOL)wantsTouchEvents;
@end
对于您希望可触摸的 SKNode,它们需要符合 CSTouchableNode 协议。您需要根据需要在您的课程中添加如下内容。
@property (nonatomic, assign) BOOL wantsTouchEvents;
这样做,点击节点就像我期望的那样工作。当 Apple 修复“userInteractionEnabled”错误时,它不应该中断。是的,这是一个错误。一个愚蠢的错误。傻苹果。
更新
SpriteKit 中还有另一个错误……节点的 z 顺序很奇怪。我见过奇怪的节点顺序......因此我倾向于为需要它的节点/场景强制使用 zPosition。
我已经更新了我的 SKScene 实现,以根据 zPosition 对节点进行排序。
nodes = [nodes sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"zPosition" ascending:false]]];
for( SKNode* node in nodes )
{
...
}