我的解决方案不需要使用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
如果您希望使您的SKNodes可以被触摸,则需要符合CSTouchableNode协议。您需要根据需要向您的类添加以下内容:
@property (nonatomic, assign) BOOL wantsTouchEvents;
这样做,点击节点可以按照我预期的方式工作。而且当苹果修复“userInteractionEnabled”错误时,它不应该出现问题。是的,这是一个错误,一个愚蠢的错误。愚蠢的苹果。
更新
SpriteKit中还有另一个bug……节点的z顺序很奇怪。我曾经见过节点的奇怪排序……因此我倾向于为需要的节点/场景强制设置zPosition。
我已更新我的SKScene实现,根据zPosition对节点进行排序。
nodes = [nodes sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"zPosition" ascending:false]]]
for( SKNode* node in nodes )
{
...
}