【问题标题】:How to call an object's methods in touchesBegan when touched?触摸时如何在touchesBegan中调用对象的方法?
【发布时间】:2015-06-08 20:33:50
【问题描述】:

所以在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];
        }
}

气球.h

@interface Balloon : SKSpriteNode

-(void)shrink;

@end

气球.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.hBalloon.m 文件吗?
  • 以及将气球名称设置为@"balloon"
  • 实现目标的另一种方法是对气球对象进行唯一命名,将它们添加到数组中(就像你做的那样),枚举数组以找到按名称触摸的气球,然后运行收缩方法。
  • @BenKane 我已经添加了 .h 和 .m 文件。
  • 您确实意识到在您的 init 方法中您正在向气球添加气球?

标签: objective-c sprite-kit touchesbegan


【解决方案1】:

问题在于您的气球初始化。您正在创建子 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];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多