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

4

我正在尝试为我的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个回答

3
在你的精灵类中添加一个粒子系统的实例变量。然后,在创建粒子效果时,不要将其添加到精灵本身,而是添加到某个更高级别的节点。这可以是主游戏层或场景,或者你可以简单地使用 self.parent.parent,它会给你精灵批处理节点的父节点。
然后在精灵类中安排一个更新方法。如果粒子系统不为空,则将其位置设置为精灵的位置。需要的话还可以加上偏移量。
完成了:
-(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;
    }
}

可以了!谢谢!我从来不知道你可以这样做,比如self.parent.parent。 - SkyTeck Games

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接