Question

How can I perform an action when I sprite is touched I currently use the node method and it checks the name of the sprite but is there any way to make it more accurate and responsive each time a sprite is touched.

In short : How can I perform an action when a sprite is touched by a user?

Was it helpful?

Solution

I am not sure what you mean by the name of the sprite but I think the code sample below is the best way to check which SKSpriteNode has been touched.

#import "MyScene.h"

@implementation MyScene
{
    SKSpriteNode *frank;
    SKSpriteNode *sally;
}

-(id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size])
    {
        frank = [SKSpriteNode spriteNodeWithColor:[SKColor blueColor] size:CGSizeMake(50, 50)];
        frank.position = CGPointMake(100, 100);
        [self addChild:frank];

        sally = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(50, 50)];
        sally.position = CGPointMake(300, 100);
        [self addChild:sally];
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInNode:self.scene];

    if (CGRectContainsPoint(frank.frame, touchLocation))
        NSLog(@"Frank");

if (CGRectContainsPoint(sally.frame, touchLocation))
        NSLog(@"Sally");
}

-(void)update:(CFTimeInterval)currentTime
{
    //
}

@end

UPDATED for additional question

You could check for the node's position like this:

if ((CGRectContainsPoint(sally.frame, touchLocation)) & (sally.position.y > 50))
    NSLog(@"Sally's y position: %f",sally.position.y);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top