public
Last active

  • Download Gist
TouchPriority.h
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//
// SKNode+TouchPriority.h
// ButtonLab
//
// Created by Fille Åström on 10/20/13.
// Copyright (c) 2013 IMGNRY. All rights reserved.
//
 
#import <SpriteKit/SpriteKit.h>
 
@interface SKNode (TouchPriority)
 
- (NSString *)nodeDepthPriority;
 
@end
TouchPriority.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
//
// SKNode+TouchPriority.m
// ButtonLab
//
// Created by Fille Åström on 10/20/13.
// Copyright (c) 2013 IMGNRY. All rights reserved.
//
 
#import "TouchPriority.h"
 
@implementation SKNode (TouchPriority)
 
- (NSString *)nodeDepthPriority {
__block NSString *code = @"";
SKNode *currentNode = self;
while (currentNode.parent) {
[currentNode.parent.children enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if (obj == currentNode) {
code = [NSString stringWithFormat:@"%03d%@", (int)idx, code];
*stop = YES;
}
}];
currentNode = currentNode.parent;
}
return code;
}
 
@end
 
@implementation SKScene (TouchPriority)
 
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
SKNode *nodeToTouch = [self nodeWithHighestPriority:touches];
[nodeToTouch touchesBegan:touches withEvent:event];
}
 
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
SKNode *nodeToTouch = [self nodeWithHighestPriority:touches];
[nodeToTouch touchesEnded:touches withEvent:event];
}
 
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
SKNode *nodeToTouch = [self nodeWithHighestPriority:touches];
[nodeToTouch touchesCancelled:touches withEvent:event];
}
 
- (SKNode *)nodeWithHighestPriority:(NSSet *)touches {
// Only allow touches to be receieved by nodes with userInteractionEnabled, and only the one with the highest touch priority
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInNode:self];
NSArray *touchedNodes = [self nodesAtPoint:touchLocation];
SKNode *nodeToTouch = nil;
for (SKNode *node in touchedNodes) {
if (node.userInteractionEnabled && node.hidden == NO && node.alpha > 0) {
if (nodeToTouch == nil) {
nodeToTouch = node;
}
else if (node.parent == nodeToTouch.parent && node.zPosition > nodeToTouch.zPosition) {
nodeToTouch = node;
}
else if (node.parent == nodeToTouch.parent && node.zPosition == nodeToTouch.zPosition && [[nodeToTouch nodeDepthPriority] compare:[node nodeDepthPriority]] == NSOrderedAscending) {
nodeToTouch = node;
}
else if (node.parent != nodeToTouch.parent && [[nodeToTouch nodeDepthPriority] compare:[node nodeDepthPriority]] == NSOrderedAscending) {
nodeToTouch = node;
}
}
}
return nodeToTouch;
}
 
@end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.