PlantManager.h
#ifndef _PlantManager_H_
#define _PlantManager_H_
#include "cocos2d.h"
#include "cocos-ext.h"
#include "Character.h"
#include "EnumPlantType.h"
#include <vector>
using namespace std;
class PlantManager : public CCLayer
{
public:
PlantManager();
~PlantManager();
CREATE_FUNC(PlantManager);
virtual bool init();
virtual void onExit();
void createPlants(const vector<PlantType> &v, const vector<CCPoint> &vp);
private:
CCArray* m_plants;
};
#endif
PlantManager.cpp
#include "PlantManager.h"
#include <cstring>
PlantManager::PlantManager()
{
m_plants = NULL;
}
//
PlantManager::~PlantManager()
{
}
//
bool PlantManager::init()
{
bool bRet = false;
do{
CC_BREAK_IF(! CCLayer::init());
CCTexture2D::PVRImagesHavePremultipliedAlpha(true);
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("PvZres2/peashooter.plist");
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("PvZres2/plants_type.plist");
bRet = true;
}while(0);
return bRet;
}
//
void PlantManager::onExit()
{
CCSpriteFrameCache::sharedSpriteFrameCache()->removeSpriteFrameByName("PvZres2/peashooter.plist");
CCSpriteFrameCache::sharedSpriteFrameCache()->removeSpriteFrameByName("PvZres2/plants_type.plist");
}
//
void PlantManager::createPlants(const vector<PlantType> &v, const vector<CCPoint> &vp)
{
m_plants = CCArray::createWithCapacity(v.size());
for(int i=0; i<(int)v.size(); ++i)
{
char name[64], picture[64];
int numFrames;
switch(v[i])
{
case en_CherryBomb:
numFrames = 8;
strcpy(name, "CherryBomb");
break;
case en_ScaredyShroom:
numFrames = 17;
strcpy(name, "ScaredyShroom");
break;
case en_IcePea:
numFrames = 15;
strcpy(name, "IcePea");
break;
case en_SunFlower:
numFrames = 18;
strcpy(name, "SunFlower");
break;
case en_Threepeater:
numFrames = 16;
strcpy(name, "Threepeater");
break;
case en_WallNut:
numFrames = 16;
strcpy(name, "WallNut");
break;
case en_PeaShooter:
numFrames = 13;
strcpy(name, "peashooter");
break;
default:
numFrames = 13;
strcpy(name, "peashooter");
break;
}
sprintf(picture, "%s%03d.png", name, 1);
CCSprite* sprite = CCSprite::createWithSpriteFrameName(picture);
sprite->setPosition(vp[i]);
this->addChild(sprite);
// put into array
m_plants->addObject(sprite);
CCArray* animFrames = CCArray::createWithCapacity(numFrames);
for(int i=1; i<=numFrames/*magic number*/; ++i)
{
sprintf(picture, "%s%03d.png", name, i);
CCSpriteFrame* frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(picture);
animFrames->addObject(frame);
}
CCAnimation* animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1f);
animation->setLoops(-1);
sprite->runAction(CCAnimate::create(animation));
}
}
EnumPlantType.h
#ifndef _EnumPlantType_H_
#define _EnumPlantType_H_
enum PlantType
{
en_PeaShooter = 1,
en_CherryBomb,
en_ScaredyShroom,
en_IcePea,
en_SunFlower,
en_Threepeater,
en_WallNut
};
enum ZombieType
{
en_NormalZombie = 1,
en_BucketheadZombie,
en_ConeheadZombie,
en_FlagZombie
};
#endif