[Animations] cocos2d-x 에니메이션 적용하기

|

Animations

Frame Animation

아래와 같이 여러개의 이미지 파일로 애니메이션을 만들 수 있다.

 1CCAnimation *animation = CCAnimation::create();
 2
 3// load image file from local file system to CCSpriteFrame, then add into CCAnimation
 4for (int i = 1; i < 15; i++)
 5{
 6    char szImageFileName[128] = {0};
 7    sprintf(szImageFileName, "Images/grossini_dance_%02d.png", i);
 8    animation->addSpriteFrameWithFileName(szImageFileName);  
 9}
10
11animation->setDelayPerUnit(2.8f / 14.0f); // 14개의 이미지를 2.8초 동안 보여줄때 각 프레임 간격.
12animation->setRestoreOriginalFrame(true); // 14개의 이미지를 돌린다음에 다시 1프레임으로 돌아간다
13
14CCAnimate *action = CCAnimate::create(animation);
15sprite->runAction(action);  // run action on sprite object

Note that CCAnimation is composed by sprite frames, delay time per frame, durations etc, it's a pack of "data". While CCAnimate is an action, it is created base on CCAnimation object.


Sprite Sheet Animation

위 에니메이션 방식은 이해하기 쉽지만, 실제 게임에서는 잘 사용되지 않습니다, 대신 스프라이트 시트 에니메이션을 일반적으로 사용합니다.

다음은 일반적인 스프라이트 시트입니다. 그것은 애니메이션 스프라이트 프레임 시퀀스이거나 같은 장면에서 사용될 이미지 팩이 될 수있다.


Creating from .png and .plist file

CCSpriteSheet 는 1.x  버전이나 그 이하 버전에서 사용되었지만. 2.x 이상 버전에서는 CCSpriteBatchNode 를 사용한다.
CCSpriteBatchNode는 사실상 스프라이트 프레임 이미지 텍스쳐 이다.  너는 반드시 Scene에 이것을 add해야됩니다. 이것은 add를 해도 실제로는 그려지지 않지만
렌더링 파이프 라인의 일부가 됩니다.
예를들면:
1CCSpriteBatchNode* spritebatch = CCSpriteBatchNode::create("animations/grossini.png");

그다음에 너는 CCSpriteFrameCache 싱글톤 클래스를 사용하여 plist 파일을 로드합니다.

1CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
2cache->addSpriteFramesWithFile("animations/grossini.plist"); 

CCSpriteBatchNode와 프레임이로드 및 스프라이트 시트를 장면에 추가되면, 당신은 "createWithSpriteFrameName"방법을 사용하고, CCSpriteBatchNode  자식으로 추가하여 이러한 프레임을 사용 스프라이트를 만들 수 있습니다 :

1m_pSprite1 = CCSprite::createWithSpriteFrameName("grossini_dance_01.png");
2spritebatch->addChild(m_pSprite1);
3addChild(spritebatch);

createWithSpriteFrameName

 이 메서드는  posit 파일을 이용하여 해당되는 사각형 영역을 찾을수 있습니다.

CCArray 오브젝트에 에니메이션 프레임을 더합니다. 에니메이션 사이즈는 14 프레임이고 우리는 이것을 사용하면 됩니다.

 1CCArray* animFrames = CCArray::createWithCapacity(15);
 2
 3char str[100] = {0};
 4
 5for(int i = 1; i < 15; i++) 
 6{
 7    sprintf(str, "grossini_dance_%02d.png", i);
 8    CCSpriteFrame* frame = cache->spriteFrameByName( str );
 9    animFrames->addObject(frame);
10}

마지막으로 우리는 CCAnimate 만들고 CCSprite에 runAction을 해줍니다. CCRepeatForever를 이용해서 무한으로 에니메이션을 돌릴수 있습니다.

1CCAnimation* animation = CCAnimation::createWithSpriteFrames(animFrames, 0.3f);
2m_pSprite1->runAction( CCRepeatForever::create( CCAnimate::create(animation) ) );


File animation

CCAnimationCache can load a xml/plist file which well describes the batch node, sprite frame names and their rectangles. The interfaces are much easier to use.

1CCAnimationCache *cache = CCAnimationCache::sharedAnimationCache(); // "caches" are always singletons in cocos2d
2cache->addAnimationsWithFile("animations/animations-2.plist");
3CCAnimation animation = cache->animationByName("dance_1");  // I apologize for this method name, it should be getAnimationByName(..) in future versions
4CCAnimate animate = CCAnimate::create(animation);  // Don't confused between CCAnimation and CCAnimate :)
5sprite->runAction(animate);


Trackback 0 And Comment 0

[디자인패턴] cocos2d-x 싱글톤 싱글턴 패턴 구현

|


#ifndef __SINGLETON_H__

#define __SINGLETON_H__

 

#include "cocos2d.h"

 

class SingletonClass{

private:

                  static SingletonClass * instance ;

                  ~SingletonClass(){/*empty*/};

                  SingletonClass(){

                                   value = 10;};

public:

                  static SingletonClass * getInstance();

                  static void releaseInstance();

 

                  int value;

                 

};

#endif

 

 

#include "Singleton.h"

 

SingletonClass * SingletonClass::instance = NULL ;

 

SingletonClass * SingletonClass::getInstance()

{

                  if (!instance)

                  {

                                   instance = new SingletonClass();

                  }

 

                 return instance;

}

 

void SingletonClass::releaseInstance()

{

                  if(instance) delete instance;

}

 



사용법

#include "Singleton.h"

CCLOG("VALUE %d", SingletonClass::getInstance()->value);

이런식으로 접근가능


Trackback 0 And Comment 0

[Action] cocos2d-x 액션 사용법

|


Actions



Actions 클래스는 CCNode 를 상속받는 모든 객체에 명령을 부여합니다. 액션은  오브젝트의 위치, 회전, 크기 기타등등 값들을 수정합니다

일정기간동안 수정하는 작업이면 -> CCIntervalAction actions 그렇지 않으면 -> CCInstantAction 입니다.

 예를들면 CCMoveBy는 일정기간동안 수정합니다. CCIntervalAction 액션입니다.

액션의 사용 예:

1// 스프라이트가 오른족으로  50 픽셀, 밑으로 10 픽셀 움직임 2초동안.
2CCActionInterval*  actionBy = CCMoveBy::create(2, ccp(50,10));


가속 관련된 액션들 (점점 빨라지거나 느려지는등)

  • CCEaseIn
  • CCEaseOut
  • CCEaseInOut
  • CCSpeed
    Etc. (See the ActionsEaseTest.cpp example for more info)

CCActionManager를 사용하면 중간에 액션을 일시정지 하고 재시작 할수도있다.(해당객체의)

1// Pause actions
2CCDirector *director = CCDirector::sharedDirector();
3m_pPausedTargets = director->getActionManager()->pauseAllRunningActions();
4// resume actions
5CCDirector *director = CCDirector::sharedDirector();
6director->getActionManager()->resumeTargets(m_pPausedTargets);

Basic Actions

Basic actions are the ones that modify basic properties like:

Position(위치수정관련)

CCMoveBy
CCMoveTo
CCJumpBy
CCJumpTo
CCBezierBy
CCBezierTo
CCPlace

Scale(크기수정관련)

CCScaleBy
CCScaleTo

Rotation(회전)

CCRotateBy
CCRotateTo

Visibility(보이는거)

CCShow
CCHide
CCBlink
CCToggleVisibility

Opacity(알파값)

CCFadeIn
CCFadeOut
CCFadeTo

Color(색깔)

CCTintBy
CCTintTo

Example:

1CCSprite *sprite = CCSprite::create("Images/grossini.png");
2sprite->setPosition(ccp(100, 100));
3addChild(sprite);
4
5CCMoveBy* act1 = CCMoveBy::create(0.5, ccp(100, 0));
6sprite->runAction(CCRepeat::create(act1, 1));

The act1 will be a CCMoveBy action of duration 0.5, but with the position value of ccp(100,0).


 뒤에 By 붙는거와 To 붙는거 차이


By는 현재 값 기준으로 변경 To는 그냥 그런거 상관없이 변경

만약 현재 캐릭터 위치가 120 .30 이면

만약 CCMoveBy::create(2, ccp(50,10));    //현재 캐릭터 위치 기준으로 50,10만큼 이동 -> 170,40

       CCMoveTo::create(2ccp(50,10));      //좌표값에 50, 10으로 이동 -> 50,10


Trackback 0 And Comment 0