【问题标题】:Using particle effects in cocos2d with ccspritebatchnode在 cocos2d 中通过 ccspritebatchnode 使用粒子效果
【发布时间】:2012-07-25 22:57:56
【问题描述】:

我正在尝试为我的 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];      
}

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

任何帮助将不胜感激。

【问题讨论】:

    标签: iphone cocos2d-iphone ccparticlesystem


    【解决方案1】:

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

    然后在 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;
        }
    }
    

    【讨论】:

    • 有效!谢谢!我不知道你可以做一些事情,比如 self.parent.parent。
    猜你喜欢
    • 2023-04-03
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多