2013년 12월 4일 수요일

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


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


CustomSprite.h
  1. #ifndef __Fortune__CustomSprite__
  2. #define __Fortune__CustomSprite__
  3.  
  4. #include "Common.h"
  5.  
  6. class CustomSprite:public CCSprite
  7. {
  8. public:
  9. CustomSprite();
  10. ~CustomSprite();
  11. static CustomSprite* create(CCSpriteBatchNode* batchNode, int Type);
  12. void showBag();
  13. private:
  14. static const char* fileName(int Type);
  15. };
  16.  
  17. #endif /* defined(__Fortune__CustomSprite__) */

CustomSprite.cpp
  1. #include "CustomSprite.h"
  2.  
  3. CustomSprite::CustomSprite(){}
  4. CustomSprite::~CustomSprite(){}
  5.  
  6. CustomSprite* CustomSprite::create(CCSpriteBatchNode* batchNode, int Type)
  7. {
  8. CCSpriteFrame* frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(fileName(Type));
  9. CustomSprite* custom = new CustomSprite();
  10. if (custom && custom->initWithSpriteFrame(frame))
  11. {
  12. batchNode->addChild(custom, 1);
  13. ///////////////////////////////////////////////////////////////
  14. // 자식 스프라이트 추가
  15. ///////////////////////////////////////////////////////////////
  16. CCSprite* child = CCSprite::createWithSpriteFrameName("child.png");
  17. child->setTag(1);
  18. child->setPosition(ccp(142.0f, 75.0f));
  19. custom->addChild(child, -1); // 자식 스프라이트를 부모 스프라이트의 아래 위치시킴
  20. child->setVisible(false); // 자식 스프라이트를 화면에서 숨김
  21. return custom;
  22. }
  23. CC_SAFE_DELETE(custom);
  24. return NULL;
  25. }
  26.  
  27. #pragma mark -
  28. #pragma mark 자식 스프라이트의 visible상태 설정
  29. void CustomSprite::showchild()
  30. {
  31. this->getChildByTag(1)->setVisible(true);
  32. }
  33. #pragma mark -
  34. #pragma mark 타입을 int 받아서 char*형 파일 이름을 리턴
  35. const char* CustomSprite::fileName(int Type)
  36. {
  37. std::string name = "custom_";
  38. std::stringstream type;
  39. type << Type;
  40. name += type.str();
  41. name += ".png";
  42. return name.c_str();
  43. }