您的位置:首页 > 其它

生成sprite动画对象的方法

2012-02-17 20:08 204 查看
以下只是一个最原始的方法,从执行效率的角度出发,如果一个场景里面同时包含了100个使用相同动画的sprit,
每个 动画sprite都由下面的方法生成的话,有些代码:
1.缓冲sprite帧和纹理;
2.创建一个精灵节点;
3.收集帧列表;
这些个只需要执行一次的操作便被重复执行了 100次,浪费cpu,浪费电池电量。。
所以说,还是存在相当大的优化空间。。。

- (CCSprite*) genAnimSprite:(CGPoint)position 
                   animName:(NSString*)animName 
                 startIndex:(int)startIndex 
                   endIndex:(int)endIndex 
              repeatForever:(BOOL)repeatForever 
                      delay:(float)delay 
{
   // 1.缓冲sprite帧和纹理
   
NSString *spriteFrameCacheName = [NSStringstringWithFormat:@"%@.plist", animName];
    [[CCSpriteFrameCachesharedSpriteFrameCache]
addSpriteFramesWithFile:spriteFrameCacheName];
    

    // 2.创建一个精灵批处理结点
   
NSString *spriteSheetName = [NSString
stringWithFormat:@"%@.png", animName];
   
CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNodebatchNodeWithFile:spriteSheetName];
    [_single.gameLayeraddChild:spriteSheet];
    
   // 3.收集帧列表
   NSMutableArray *animFrames = [NSMutableArrayarray];
   
for(int i = startIndex; i < endIndex+1; ++i) {
       CCSpriteFrameCache *frameCache = [CCSpriteFrameCachesharedSpriteFrameCache];
       
NSString *frameName = [NSString
stringWithFormat:@"%@%d.png", animName, i];
       
CCSpriteFrame *spriteFrame = [frameCache spriteFrameByName: frameName];
        [animFrames
addObject: spriteFrame];
    }
    
   // 4.创建动画对象
   
CCAnimation *animation = [CCAnimation
animationWithFrames:animFrames delay:delay];
   id action = [CCAnimateactionWithAnimation:animation
restoreOriginalFrame:NO];
   
id animSequence = nil;
   
if(repeatForever == YES) {
       
id repeatAction = [CCRepeatForever
actionWithAction:action];
        animSequence = [CCSequenceactions:repeatAction,
nil];
    }
else {
       
id callFunc = [CCCallFuncN
actionWithTarget:self
selector:@selector(removeSprite:)];
        animSequence = [CCSequenceactions:action, callFunc,
nil];
    }

   // 5.创建 sprite
并且让它 run
动画 action~
   
NSString *str = [NSString
stringWithFormat:@"%@%d.png", animName, startIndex];
   
CCSprite *animSprite = [CCSprite
spriteWithSpriteFrameName:str];
   
CGSize size = [self
getAnimSpriteSize:animName start:startIndex];
   
if(!_isIpad) {
        [animSprite
setContentSize:size]; //只有这种方法才是有效的~
    }
else {
       
CGSize ipadSize = CGSizeMake(2*size.width,2*size.height);
        [animSprite
setContentSize:ipadSize];
    }
    [_single.gameLayeraddChild:animSprite];
    [animSprite
setPosition:position];
    [animSprite
runAction:animSequence];
    
   
return animSprite;
}

/**
待气球爆炸动作执行完毕之后,将 animSprite 从 gameLayer中移除~ */
- (void) removeSprite:(id)sender {
//    NSLog(@"回调函数被调用~");
   
CCSprite *animSprite = (CCSprite*)sender;
    [_single.gameLayerremoveChild:animSprite
cleanup:YES];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐