Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect all nodes or specific nodes in a touchBegins

Tags:

ios

sprite-kit

In iOS 7's SpriteKit framework, I am attempting to build a simple game for the purposes of learning the framework. One area I am tripping over a little bit is how to detect a specific node when there are multiple nodes overlapping under a touch. Let me give an example:

In a basic chess training game, I can drag a piece forward one tile, but what happens after that is dependent on what other nodes are in that space. I want to know which tile the touch is on, regardless of any other nodes which happen to also be on that tile node. The problem I am running into is that the touch seems to detect the uppermost node. So my question would be:

What is the recommended solution for detecting the tile node? I was thinking about using zPosition in some way but I have yet to determine how to do that. Any suggestions?

Another approach would be to detect ALL nodes under a touch. Is there a way to grab all nodes and put them in an array?

like image 354
zeeple Avatar asked Dec 15 '22 05:12

zeeple


1 Answers

Iterate through the nodes at the touched point:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    NSArray *nodes = [self nodesAtPoint:[touch locationInNode:self]];
    for (SKNode *node in nodes) {
       //go through nodes, get the zPosition if you want
       int nodePos = node.zPosition;

       //or check the node against your nodes
       if ([node.name isEqualToString:@"myNode1"]) {
           //...
       }

       if ([node.name isEqualToString:@"myNode2"]) {
           //...
       }
    }
}
like image 88
AndyOS Avatar answered Dec 17 '22 17:12

AndyOS