2013년 12월 4일 수요일

자식 Sprite를 포함한 사용자 정의 CCSprite - cocos2d-x


  • 자식 Sprite를 포함하는 사용자 정의 CCSprite를 정의
  •  멤버함수 Showchild를 통해 자식 Sprite의 상태(Position, Visible 등)를 제어


CustomSprite.h
#ifndef __Fortune__CustomSprite__
#define __Fortune__CustomSprite__

#include "Common.h"

class CustomSprite:public CCSprite
{
public:
    CustomSprite();
    ~CustomSprite();
    static CustomSprite* create(CCSpriteBatchNode* batchNode, int Type);
    
    void showBag();
    
private:
    static const char* fileName(int Type);
};

#endif /* defined(__Fortune__CustomSprite__) */

CustomSprite.cpp
#include "CustomSprite.h"

CustomSprite::CustomSprite(){}
CustomSprite::~CustomSprite(){}

CustomSprite* CustomSprite::create(CCSpriteBatchNode* batchNode, int Type)
{
    CCSpriteFrame* frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(fileName(Type));
    
    CustomSprite* custom = new CustomSprite();
    if (custom && custom->initWithSpriteFrame(frame))
    {
        batchNode->addChild(custom, 1);
        
        ///////////////////////////////////////////////////////////////
        // 자식 스프라이트 추가
        ///////////////////////////////////////////////////////////////
        CCSprite* child = CCSprite::createWithSpriteFrameName("child.png");
        child->setTag(1);
        child->setPosition(ccp(142.0f, 75.0f));
        custom->addChild(child, -1); // 자식 스프라이트를 부모 스프라이트의 아래 위치시킴
        child->setVisible(false);    // 자식 스프라이트를 화면에서 숨김
        
        return custom;
    }
    
    CC_SAFE_DELETE(custom);
    return NULL;
}

#pragma mark -
#pragma mark 자식 스프라이트의 visible상태 설정
void CustomSprite::showchild()
{
    this->getChildByTag(1)->setVisible(true);
}
#pragma mark -
#pragma mark 타입을 int로 받아서 char*형 파일 이름을 리턴
const char* CustomSprite::fileName(int Type)
{
    std::string name = "custom_";
    
    std::stringstream type;
    type << Type;
    
    name += type.str();
    name += ".png";
    
    return name.c_str();
}