触摸时如何在touchesBegan中调用对象的方法?

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

所以在 MyScene.m 中,我创建了气球对象并将其放入场景中。

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];
}

我的屏幕上出现了 4 个气球。在 Balloon.h 文件中,我有一个名为 -(void)shrink 的方法,我想在 -(void)touchesBegan 方法内的点击气球对象上调用它。我在下面尝试过这段代码,但它给了我一个 NSInvalidArgumentException', reason: '-[SKSpriteNode shrink]: unrecognized selector sent to instance 0x17010c210' 错误。

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
}

问题出在您的气球初始化中。您没有使用 Balloon class 创建子 SKSpriteNode 并将名称设置为 balloon。这就是为什么您得到的是 SKSpriteNode 而不是气球。

你也可以这样做。

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

在您创建气球的场景中

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