[Cocos2D 09.03]05. AtlasAnimation과 Sprite

2010. 9. 3. 15:24IPhone/Cocos2D

1.sprite 생성

-(void)gogo
{
      NSString str=[[NSString alloc] initWithFormat:@"%d.png",i];
      Sprite *sp=[Sprite spriteWithFile: str];
      [sp setPosition:ccp(240,160)];
      sp.visible=NO;
      [self addChild:sp z:0];
}
@end

2.AtlasAnimation
스프라이트 메니져 생성->레이어나 씬에 메니져 등록->스프라이트 메니져 사용->스프라이트 이미지 생성->스프라이트 이미지 매니져 등록->스프라이트 애니메이션 생성->스프라이트 액션 생성

스프라이트 메니져 생성
 AtlasSpriteManager *mgr = [AtlasSpriteManager spriteManagerWithFile:@"kriel_spr04.png" capacity:100];

레이어나 씬에 메니져 등록

[self addChild:mgr z:0 tag:tagSpriteManager];

스프라이트 메니져 사용

 AtlasSpriteManager *mgr = (AtlasSpriteManager*) [self getChildByTag:tagSpriteManager];

스프라이트이미지 생성
 AtlasSprite *sprite = [AtlasSprite spriteWithRect:CGRectMake(x, y,w, h) spriteManager:mgr];
sprite.position = ccp(sx, sy);

스프라이트 이미지 매니져 등록
 [mgr addChild:sprite z:1 tag:tagHero];

스프라이트 애니메이션 생성

AtlasAnimation *slimAnim = [self makeAnimation:@"slime" andNumFrames:4];
-(AtlasAnimation*) makeAnimation: (NSString*)animationName andNumFrames:(int)frames
{
         AtlasAnimation *animation = [AtlasAnimation animationWithName:animationName delay:0.2f];
         for (int i=0; i<frames; i++)
         {
                 [animation addFrameWithRect: CGRectMake(0+i*40, 0, 40, 40) ];
         }
         return animation;
}

스프라이트 액션 생성
Action* slimeAction = [RepeatForever actionWithAction:[Animate actionWithAnimation: slimAnim]];

3.기타 다른 기능들...

현재 매니져가 가지고 있는 스프라이트 가져오기
AtlasSpriteManager *mgr = (AtlasSpriteManager*) [self getChildByTag:tagSpriteManager];
AtlasSprite *sprite = (AtlasSprite*)[mgr getChildByTag:tagHero];

애니메이션 멈춤

[sprite stopAction:currentHeroAction];

애니메이션 실행
self.currentHeroAction = heroLeftAction;
[s runAction:heroLeftAction];

실질적으로 그리기 위한 액션
 [self addAction:sprite at:i and:j];

-(void) addAction:(AtlasSprite*)sprite at:(int)x and:(int)y

         byte b = getStage(x, y);
         // slime
         if (b == IMG_SLIME /*3*/)
         {
                   id action = [[slimeAction copy] autorelease];
                   [sprite runAction:action];
         }
}



실제 애니메이션을 하기 유용한 방법
 -(AtlasAnimation*) makeAnimation: (NSString*)animationName andNumFrames:(int)frames
{
          AtlasAnimation *animation = [AtlasAnimation animationWithName:animationName delay:0.2f];
          SpriteElement *elem;
          for (int i=0; i<frames; i++)
         {
                    NSString* animFilename = [NSString stringWithFormat:@"%@%d.png", animationName, i+1];
                    elem = [spriteDirctionay objectForKey:animFilename];
                    if (elem)
                            [animation addFrameWithRect: CGRectMake(elem.x, elem.y, elem.w, elem.h) ];
                    else
                            return nil;
         }
         return animation;
}