使用Tiled地图编辑器编辑原本的地图,在地图中添加enemy图层,并添加图块,即可完成敌人的添加。
为了完成Hero与Enemy的碰撞检测,创建一个Enemy类用来保存Enemy的Gid和position
class CEnemy : public CCObject
{
public:
CEnemy();
~CEnemy();
virtual bool init();
CCPoint getPos() { return m_pos;};
void setPos(CCPoint cp) { m_pos=cp; };
int getGid() { return m_gid; };
void setGid(int gid) { m_gid=gid; };
CREATE_FUNC(CEnemy);
protected:
CCPoint m_pos;
int m_gid;
};
在Gamemap添加enemeylayer,并在初始化中遍历地图,并存储Enemy到CCArray中
enemyLayer=this->layerNamed("enemy");
CCSize size=enemyLayer->getLayerSize();
for (int i=0;itileGIDAt(ccp(i,j));
if (gid!=0)
{
CEnemy * enemy;
enemy=CEnemy::create();
enemy->setGid(gid);
enemy->setPos(ccp(i,j));
m_enemyArray->addObject(enemy);
}
}
}
接下来在游戏中添加战斗,英雄碰到敌人后会自动发生战斗,敌人在战斗时会改变颜色,在英雄头上显示被扣的生命,战斗结束后怪物消失,
首先创建战斗时效果,发生战斗时,取得正在战斗的敌人,并创建一个定时器,使得敌人反复变成红白两色5次,然后销毁定时器
void GameMap::showEnemyHit(CCPoint cp)
{
m_fightCount=0;
m_fightingEnemy=enemyLayer->tileAt(cp);
if (m_fightingEnemy==NULL)
{
return;
}
m_fightingEnemy->setColor(ccRED);
this->schedule(schedule_selector(GameMap::updateEnemyHit),0.2f);
}
void GameMap::updateEnemyHit(float dt)
{
m_fightCount++;
if (m_fightCount % 2 ==1)
{
m_fightingEnemy->setColor(ccWHITE);
CCLOG("%d",m_fightCount);
}
else{
m_fightingEnemy->setColor(ccRED);
}
if(m_fightCount==5)
unschedule(schedule_selector(GameMap::updateEnemyHit));
}
创建一个文本标签,将会在战斗时显示英雄掉血,并创建一个回调函数,当战斗完成时销毁标签并使当前敌人消失
bool Hero::showTip(const char * tip,CCPoint startPos)
{
CCLabelTTF * tipLabel=CCLabelTTF::create(tip,"Arial",20);
tipLabel->setPosition(ccpAdd(startPos,ccp(16,16)));
this->addChild(tipLabel,KTip,KTip);
CCAction * action=CCSequence::create(
CCMoveBy::create(0.5,ccp(0,32)),
CCDelayTime::create(0.5f),
CCFadeOut::create(0.2f),
CCCallFuncN::create(this,callfuncN_selector(Hero::onShowTipDown)),
NULL
);
tipLabel->runAction(action);
return true;
}
void Hero::onShowTipDown(CCNode* pSender)
{
this->getChildByTag(KTip)->removeFromParentAndCleanup(true);
GClassManagerInstance->g_gameMap->getEnemyLayer()->removeTileAt(m_targetPos);
}
创建战斗调用,此时英雄掉血只是一个固定的数据
void Hero::fight()
{
char temp[30]={0};
sprintf(temp,"lost hp : -%d",100);
showTip(temp,getPosition());
}
最后在碰撞检测中进行相关调用
if(GClassManagerInstance->g_gameMap->checkCollision(targetPosition)==Enemy)
{
fight();
}
CollisionType GameMap::checkCollision(CCPoint heroPotion)
{
CCPoint tileCoord=positionToTileCoord(heroPotion);
/*``````````
````````````*/
tileGid=this->getEnemyLayer()->tileGIDAt(tileCoord);
if (tileGid)
{
showEnemyHit(tileCoord);
return Enemy;
}
return Moveble;
}