2016-03-02 29 views
1

我正在使用Objective-C在SpriteKit中制作游戏。我有继承SKNode类:SpriteKit/Objective-C - 节点内的触摸检测

@interface Card : SKNode 

我也随后宣布这一类中SKSpriteNodes并添加他们为孩子们:

cardSprite = [SKSpriteNode spriteNodeWithImageNamed:fileName]; //fileName corresponds with an image asset 
[self addChild:cardSprite]; 

然后我做一个卡对象,并将其添加为孩子委托给我主GameScene。我想知道如何在Card对象内的SKSpriteNode上进行触摸检测。通常我会为每个节点使用一个名称来进行触摸检测,但是当名称是从Card对象而不是GameScene中设置时,似乎并没有工作。

+0

这里已经有一些关于StackOverflow的文章了。你可以从这开始:http://stackoverflow.com/a/19489006/3402095 – Whirlwind

回答

0

这里是我如何做到这一点:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    UITouch *touch = [touches anyObject]; 
    CGPoint location = [touch locationInNode:self]; 
    [self handleTouchedPoint:location]; // Cleans 'touchesBegan' method by carrying over needed code elsewhere. 
} 

/** Handle touches. */ 
- (void)handleTouchedPoint:(CGPoint)touchedPoint { 
    SKNode *touchedNode = [self nodeAtPoint:touchedPoint]; 

    // Detects which node was touched by utilizing names. 
    if ([touchedNode.name isEqualToString:@"God"]) { 
     NSLog(@"Touched world"); 
    } 
    if ([touchedNode.name isEqualToString:@"Tiles"]) { 
     NSLog(@"Touched map"); 
    } 
    if ([touchedNode.name isEqualToString:@"Player Character"]) { 
     NSLog(@"Touched player"); 
    } 
    if ([touchedNode.name isEqualToString:@"Test Node"]) { 
     NSLog(@"Touched test node"); 
    } 
} 

附: 'Test Node'是在我的Player类(也是SKSpriteNode)中创建的SKSpriteNode,用于测试触摸是否仍然适用于它。他们是这样。