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



我有一小段代码,可以创建多达 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循环?

with 3.x ...使用 CCNode 的名称属性来发挥您的优势。

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

使用了一个数组

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

最新更新