cocos2d動畫用例

來源:互聯網
上載者:User

// Animation.h
#import "Box2D.h"
#import "cocos2d.h"
#import "BYSingle.h"
@interface AnimSpriteFactory : NSObject {
    BYSingle *_single;
    BOOL _is4g;
    BOOL _isIpad;
}

- (id) init;
- (CCSprite*) genAnimSprite:(CGPoint)position
                   animName:(NSString*)animName
                 startIndex:(int)startIndex
                   endIndex:(int)endIndex
              repeatForever:(BOOL)repeatForever
                      delay:(float)delay;

- (void) dealloc;
@end

 

//  Animation.mm
#import "AnimSpriteFactory.h"
@implementation AnimSpriteFactory

- (id) init {
    if((self = [super init])) {
        _single = [BYSingle getInstance];
_is4g = _single.isRetinaSupported;
_isIpad = _single.isIpad;
    }
    return self;
}

/**
 * 用於擷取 sprite 的寬度和高度,太他媽蛋疼了~
 * 解析 plist 檔案
 * 弊端:會使動畫第一幀偏低於正常情況(當初不知道是出於什麼意圖要計算齣動畫的 size)~
 */
-(CGSize) getAnimSpriteSize:(NSString*)animName start:(int)startIndex {
NSString *plistPath = [[NSBundle mainBundle] pathForResource:animName ofType:@"plist"];
NSDictionary *dictionary, *framesDic;
//
dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
   
dictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
framesDic = [dictionary objectForKey:@"frames"];
NSMutableDictionary *startFrameDic = [framesDic objectForKey:[NSString stringWithFormat:@"%@%d.png", animName, startIndex]];
NSString *rectDataString = [startFrameDic objectForKey:@"frame"];
NSRange range = NSMakeRange(1, [rectDataString length]-2);
NSString *withoutBorder = [rectDataString substringWithRange:range];
NSArray *array = [withoutBorder componentsSeparatedByString:@", "];
NSString *sizeString = [array objectAtIndex:1];
NSRange range2 = NSMakeRange(1, [sizeString length]-2);
NSString *sizeStringWithoutBorder = [sizeString substringWithRange:range2];
NSArray *size = [sizeStringWithoutBorder componentsSeparatedByString:@","];
return CGSizeMake([[size objectAtIndex:0] intValue], [[size objectAtIndex:1] intValue]);
}

// delay 預設值為 0。05~
- (CCSprite*) genAnimSprite:(CGPoint)position
                   animName:(NSString*)animName
                 startIndex:(int)startIndex
                   endIndex:(int)endIndex
              repeatForever:(BOOL)repeatForever
                      delay:(float)delay
{
    CCSpriteFrameCache *frameCache = [CCSpriteFrameCache sharedSpriteFrameCache];
   
    // 1.緩衝sprite幀和紋理
    NSString *spriteFrameCacheName = [NSString stringWithFormat:@"%@.plist", animName];
    [frameCache addSpriteFramesWithFile:spriteFrameCacheName];
   
    /**
     * 2.建立一個精靈批處理結點
     * 該步操作放在這兒不好,水動畫要用到很多個,這麼做的話就會添加進很多重複的 batchNode ~
     * Eric 將這步放置在方法的外部,是個很好的做法!
     */
    NSString *spriteSheetName = [NSString stringWithFormat:@"%@.png", animName];
    CCSpriteBatchNode *spriteBatchNode = [CCSpriteBatchNode batchNodeWithFile:spriteSheetName];
    [_single.gameLayer addChild:spriteBatchNode];
   
    // 3.收集幀列表
    NSMutableArray *frames = [NSMutableArray array];
    for(int i = startIndex; i < endIndex+1; ++ i) {
        NSString *frameName = [NSString stringWithFormat:@"%@%d.png", animName, i];
        CCSpriteFrame *spriteFrame = [frameCache spriteFrameByName: frameName];
        [frames addObject: spriteFrame];
    }
   
    // 4.建立動畫對象
    CCAnimation *animation = [CCAnimation animationWithFrames:frames delay:delay];
    id action = [CCAnimate actionWithAnimation:animation restoreOriginalFrame:NO];
    id sequence = nil;
    if(repeatForever == YES) {
        id repeatAction = [CCRepeatForever actionWithAction:action];
        sequence = [CCSequence actions:repeatAction, nil];
    } else {
        id callFunc = [CCCallFuncN actionWithTarget:self selector:@selector(removeSprite:)];
        sequence = [CCSequence actions:action, callFunc, nil];
    }

    // 5.建立 sprite 並且讓它 run 動畫 action~
    NSString *fristFrameName = [NSString stringWithFormat:@"%@%d.png", animName, startIndex];
    CCSprite *animSprite = [CCSprite spriteWithSpriteFrameName:fristFrameName];
//    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];
//    }
    [animSprite setPosition:position];
   
    /**
     * 注意:
     * 1。先 runAction 再 addChild,
     * 2。addChild 方法要由 CCSpriteBatchNode 對象調用,而不要由 _single.gameLayer 調用~
     * 由後者調用的話就失去了使用 batchNode 的意義~
     * (建立一個精靈批處理結點)
     */
    [animSprite runAction:sequence];
    [spriteBatchNode addChild:animSprite];
    return animSprite;
}

// Created by Eric~
-(CCSprite*) createAnimation:(NSString*)actionName
                      Delay:(float)delay
                 FrameCount:(int)num
                  BanchNode:(CCSpriteBatchNode*)spriteSheet
{
    CCSpriteFrameCache *frameCache = [CCSpriteFrameCache sharedSpriteFrameCache];
[frameCache addSpriteFramesWithFile:[NSString stringWithFormat:@"%@.plist",actionName]];
   
NSMutableArray *animFrames = [NSMutableArray array];
for(int i = 0; i < num ; ++ i) {
        NSString *frameName = [NSString stringWithFormat:@"%@%d.png", actionName, i];
[animFrames addObject:[frameCache spriteFrameByName:frameName]];
}
   
CCAnimation *anim = [CCAnimation animationWithFrames:animFrames delay:delay];
CCSprite *sprite = [CCSprite spriteWithSpriteFrameName:[NSString stringWithFormat:@"%@1.png", actionName]];
[sprite runAction:[CCRepeatForever actionWithAction:
  [CCAnimate actionWithAnimation:anim restoreOriginalFrame:NO]]];
[spriteSheet addChild:sprite];
return sprite;
}

/** 待氣球爆炸動作執行完畢之後,將 animSprite 從 gameLayer 中移除~ */
- (void) removeSprite:(id)sender {
    CCSprite *animSprite = (CCSprite*)sender;
    [_single.gameLayer removeChild:animSprite cleanup:YES];
}

- (void) dealloc {
    [super dealloc];
}

@end


摘自 yang3wei的專欄

相關關鍵詞:
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.