Search code examples
objective-csprite-kittouchesbegan

How to call an object's methods in touchesBegan when touched?


So in MyScene.m I create my Balloon objects and put it in the scene.

for (int i = 0; i < 4; i++) {

    Balloon *balloonObject = [[Balloon alloc] init];
    balloonObject.position = CGPointMake(50 + (75 * i), self.size.height*.5);
    [_balloonsArray addObject:balloonObject];
}

while (_balloonsArray.count > 0) {
    [self addChild:[_balloonsArray objectAtIndex:0]];
    [_balloonsArray removeObjectAtIndex:0];
}

That gives me 4 balloons on my screen. In the Balloon.h file I have a method called -(void)shrink which I want to get called on the tapped balloonObject inside the -(void)touchesBegan method. I have tried this code below but it gives me a NSInvalidArgumentException', reason: '-[SKSpriteNode shrink]: unrecognized selector sent to instance 0x17010c210' error.

for (UITouch *touch in touches) {
        CGPoint location = [touch locationInNode:self];
        Balloon *node = (Balloon *)[self  nodeAtPoint:location];

        if ([node.name isEqualToString:@"balloon"]) {

            [node shrink];
        }
}

Balloon.h

@interface Balloon : SKSpriteNode

-(void)shrink;

@end

Balloon.m

@implementation Balloon
{
    SKSpriteNode *_balloon;
}

-(id)init{

    self = [super init];
    if (self){
        _balloon = [SKSpriteNode spriteNodeWithImageNamed:@"balloonPicture"];
        _balloon.name = @"balloon";
        _balloon.position = CGPointMake(0, 0);

        [self addChild:_balloon];
    }

    return self;
}

-(void)shrink{

    // does something
}

Solution

  • The issue is in your balloon init. Instead of using the Balloon class you are creating child SKSpriteNode and setting the name to balloon. This is why you are getting a SKSpriteNode and not a Balloon.

    You could do something like this instead.

    -(id)init{
    
        self = [super init];
        if (self){
    
            self.texture = [SKTexture textureWithImageNamed:@"balloonPicture"];
            self.size = self.texture.size;
            self.name = @"balloon";
            self.position = CGPointMake(0, 0);
        }
    
        return self;
    }
    

    In your Scene where you create the balloon

    Ballon *balloon = [[Balloon alloc]init];
    [self addChild:balloon];