1

I'm making a game in SpriteKit with Objective-C. I have a class which inherits SKNode:

@interface Card : SKNode

I have then declared SKSpriteNodes inside this class and added them as children:

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

I then make a Card object and add it as a child to my main GameScene. I'm wondering how to do touch detection on the SKSpriteNode inside the Card object. Normally I would use a name for each node for touch detection, but that doesn't seem to be working when the name is set from inside the Card object rather than in GameScene.

Whirlwind
  • 14,286
  • 11
  • 68
  • 157
  • There were some posts here on StackOverflow about this already. You can start with this: http://stackoverflow.com/a/19489006/3402095 – Whirlwind Mar 03 '16 at 00:25

1 Answers1

0

Here's how I do it:

- (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");
    }
}

P.S. 'Test Node' is an SKSpriteNode created within my Player class (which is also a SKSpriteNode) to test if touches still work on it. They do.

Krekin
  • 1,516
  • 1
  • 13
  • 24