Using particle effects in cocos2d with ccspritebatchnode

I am trying to add particle effect to my cocos2d iOS game. I had a problem adding particles to my sprites because all my sprites use spritebatch to improve performance. Because of this, it seems to me that I cannot easily use the particle effect on my sprites. Everything works correctly if I just keep all the particle effects on my game layer, but I would prefer each sprite to track its own particle effect. Here is my code which is in my player class:

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

Using this method, I get an error

 CCSprite only supports CCSprites as children when using CCSpriteBatchNode 

To avoid this, I made a separate class, particleBase.

In the particleBase class, I inherit it from ccsprite and have an iVar to track the particle effect:

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

When using this technique, I tried this in my class:

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

However, I do not get an error, but the particle is also not displayed.

Any help would be greatly appreciated.

+4
source share
1 answer

Add an instance variable for the particle system to your sprite class. Then, when you create the particle effect, do not add it to the sprite itself, but to a higher level node. It can be the main game layer or scene, or you can just use self.parent.parent , which will provide you with the parent sprite node.

Then plan the update method in the sprite class. If the particle system is not zero, set its position to the position of the sprite. If necessary, offset plus.

Et voilΓ‘:

 -(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; } } 
+3
source

All Articles