在cocos2d中使用ccspritebatchnode中的粒子效果

时间:2012-07-25 22:57:57

标签: iphone cocos2d-iphone ccparticlesystem

我正在尝试为我的cocos2d iOS游戏添加粒子效果。在向我的精灵添加粒子时遇到问题,因为我的所有精灵都在使用spritebatch来提高性能。由于这个原因,我似乎不能轻易地对我的精灵使用粒子效果。如果我只是将所有粒子效果保留在我的游戏玩法层上,那么一切都能正常工作,但我宁愿让每个精灵跟踪它自己的粒子效果。这是我的代码,它位于我的播放器类中:

-(void)loadParticles  
{    
    shieldParticle = [[CCParticleSystemQuad alloc] initWithFile:@"shieldParticle.plist"];
    shieldParticle.position = self.position;
    [self addChild:shieldParticle];  
}

使用这种技术会给我一个错误

CCSprite only supports CCSprites as children when using CCSpriteBatchNode

为了避免这种情况,我创建了一个单独的类particleBase。

在particleBase类中,我从ccsprite继承它,并有一个跟踪粒子效果的iVar:

#import "cocos2d.h"
@interface particleBase : CCSprite
{
CCParticleSystem *particleEffect;
}

-(void)setParticleEffect:(NSString *)effectName;
-(void)turnOnParticles;
-(void)turnOffParticles;
@end

#import "particleBase.h"

@implementation particleBase

-(void)setParticleEffect:(NSString *)effectName
{    
    particleEffect = [[CCParticleSystemQuad alloc] initWithFile:effectName];
    particleEffect.active = YES;
    particleEffect.position = self.position;
    [self addChild:particleEffect];
}

使用这种技术时,我在我的播放器类中尝试了这个:

-(void)loadParticles
{    
    shieldParticle = [[particleBase alloc] init];
    [shieldParticle setParticleEffect:@"shieldParticle.plist"];
    [shieldParticle turnOnParticles];
    [shieldParticle setPosition:self.position];
    [self addChild:shieldParticle z:150];      
}

执行此操作时,我没有收到错误,但也没有显示粒子。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

在精灵类中为粒子系统添加一个实例变量。然后,在创建粒子效果时,不要将它添加到精灵本身,而是添加到某个更高级别的节点。这可能是主要的游戏图层或场景,或者您可以简单地使用self.parent.parent,这将为您提供精灵批处理节点的父级。

然后在sprite类中安排更新方法。如果粒子系统不是nil,则将其位置设置为精灵的位置。如果需要,还可以加偏移。

Etvoilá:

-(void) createEffect
{
    particleSystem = [CCParticleSystem blablayouknowwhattodohere];
    [self.parent.parent addChild:particleSystem];
    particleSystem.position = self.position;

    // if not already scheduled:
    [self scheduleUpdate];
}

-(void) removeEffect
{
    [particleSystem removeFromParentAndCleanup:YES];
    particleSystem = nil;

    // unschedule update unless you need update for other things too
    [self unscheduleUpdate];
}

-(void) update:(ccTime)delta
{
    if (particleSystem)
    {
        particleSystem.position = self.position;
    }
}