有没有办法通过文件名删除精灵?

时间:2014-12-30 19:31:24

标签: objective-c cocos2d-iphone

我有一小段代码可以创建多达21个特定精灵的实例。在用户创建21个精灵(通过按下按钮)之后,我希望从父级中删除所有精灵。当我试图移除21个精灵时,我遇到了障碍,因为我创建精灵的方式是每次用户点击按钮时我都会创建精灵的新实例。

-(void)createNewCactus
{
    CCSprite *newCactus = [CCSprite spriteWithImageNamed:@"cactusclipart.png"];
    [newCactus setScale:0.25];
    if (cactiCount <= 21) {
        cactiCount++;
        if (cactiCount < 7)
            [newCactus setPosition:ccp(43*cactiCount, 140)];
        else if (cactiCount < 13)
            [newCactus setPosition:ccp(43*cactiCount-258, 90)];
        else
            [newCactus setPosition:ccp(43*cactiCount-516, 40)];
        [self addChild:newCactus];
    } else {
        [newCactus removeFromParentAndCleanup:YES];
    }
}

我的问题是,有什么方法可以使用cocos2d按文件名删除所有精灵?像[self removeAllSpritesByFileName@"cactusclipart.png"];这样的东西?考虑到我正在为每个精灵创建一个新实例,这样的事情是否会起作用?事后我意识到我编写这段代码的方式可能并不是最好的,但我一直试图想到任何其他不会造成巨大混乱的方法。也许是带有NSArray的for循环?

2 个答案:

答案 0 :(得分:3)

3.x ...使用CCNode的name属性对你有利。

-(void)createNewCactus
{
    CCSprite *newCactus = [CCSprite spriteWithImageNamed:@"cactusclipart.png"];
    [newCactus setScale:0.25];
    newCactus.name = @"cactusclipart.png";
    if (cactiCount <= 21) {
        cactiCount++;
        if (cactiCount < 7)
            [newCactus setPosition:ccp(43*cactiCount, 140)];
        else if (cactiCount < 13)
            [newCactus setPosition:ccp(43*cactiCount-258, 90)];
        else
            [newCactus setPosition:ccp(43*cactiCount-516, 40)];
        [self addChild:newCactus];
    } else {
        [newCactus removeFromParentAndCleanup:YES]; // <- this will never happen
    }
}

并删除类似的内容:

CCSprite *cac;
while (cac = [self getChildByName:@"cactusclipart.png" recursively:NO]) {
   [cac revoveFromParentAndCleanup:YES];
}

答案 1 :(得分:0)

使用数组

-(void)createNewCactus
{

    CCSprite *newCactus = [CCSprite spriteWithImageNamed:@"cactusclipart.png"];
    [newCactus setScale:0.25];
    if (cactiCount < 18) {
        cactiCount++;
        if (cactiCount < 7)
            [newCactus setPosition:ccp(43*cactiCount, 140)];
        else if (cactiCount < 13)
            [newCactus setPosition:ccp(43*cactiCount-258, 90)];
        else if (cactiCount < 19)
            [newCactus setPosition:ccp(43*cactiCount-516, 40)];
        [self addChild:newCactus];
        NSLog(@"%li", (long)cactiCount);
        [spriteArray addObject:newCactus];
    } else {
        NSLog(@"should dlelete");
        for (int i = 0; i <= spriteArray.count-1; i++) {
            [spriteArray[i] removeFromParentAndCleanup:YES];
        }
    }
}
相关问题