4

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?

4

2 回答 2

12

遍历接触点的节点:

- (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"]) {
           //...
       }
    }
}
于 2013-10-11T20:50:46.467 回答
0

您可以计算给定点的图块,因为您会知道棋盘的框架,从而知道每个图块的大小。

例如,假设您有一个框架为 {10, 50, 160, 160} 的棋盘。因此,您知道每个图块的大小为 20x20。如果你在点 {x,y} 有触摸,你知道触摸行(x-10)/20的索引是 ,列的索引是(y-50)/20。哦,您可能也需要floorf在该计算中使用。

或者,要实际回答您的问题,您可以使用该nodesAtPoint:方法在给定点获取所有节点:)

于 2013-10-11T17:15:09.170 回答