我正在尝试向我的 cocos2d iOS 游戏添加粒子效果。我在向 Sprite 添加粒子时遇到问题,因为我的所有 Sprite 都使用 Sprite 批处理来提高性能。因此,我似乎无法轻松地在我的 Sprite 上使用粒子效果。如果我只是将所有粒子效果保留在游戏层上,那么一切都会正常工作,但我宁愿让每个 Sprite 跟踪自己的粒子效果。这是我的代码,位于我的玩家类中:
-(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];
}
执行此操作时,我没有收到错误,但粒子也没有显示。
任何帮助将不胜感激。
最佳答案
在 Sprite 类中添加粒子系统的实例变量。然后,当您创建粒子效果时,不要将其添加到 Sprite 本身,而是添加到一些更高级别的节点。这可能是主游戏层或场景,或者您可以简单地使用 self.parent.parent
这将为您提供 Sprite 批处理节点的父级。
然后在 Sprite 类中安排一个更新方法。如果粒子系统不为零,则将其位置设置为 Sprite 的位置。如果需要的话加上偏移量。
瞧:
-(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;
}
}
关于iphone - 在 cocos2d 中使用 ccspritebatchnode 的粒子效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11659898/