2016-03-02 56 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,用於測試觸摸是否仍然適用於它。他們是這樣。