您的位置:首页 > 移动开发 > Cocos引擎

cocos2dx打飞机项目笔记四:Enemy类和EnemyLayer类

2013-12-25 14:15 337 查看
Enemy类没什么内容,就create和init方法,根据参数来创建不同的敌机,头文件代码如下:

void EnemyLayer::addEnemy(float dt)
{
if (true)
{
int seed = 19;
int random_planeType = rand() % seed + 1;//1~19
planeType type;

Enemy* enemy = NULL;

//按概率随机生成大中小三种敌机,或者不产生
//big
if (random_planeType % 19 == 0)
{
type = bigPlane;
SimpleAudioEngine::sharedEngine()->playEffect("music/big_spaceship_flying.wav",false);
}
//mid
else if(random_planeType % 5 == 0)
{
type = midPlane;
}
//small
else if(random_planeType % 2 == 0)
{
type = smallPlane;
}
// no
else
{
return;
}

enemy = Enemy::create(type, this->batchNode->getTexture());

//初始位置(随机)
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
float x = rand() % (int)(winSize.width - (int)enemy->boundingBox().size.width * 2) + enemy->boundingBox().size.width;
float y = winSize.height - enemy->boundingBox().size.height/2;

CCPoint position = ccp(x,y);

enemy->setPosition(position);
this->m_enemys->addObject(enemy);
batchNode->addChild(enemy);

//敌机的运动轨迹CCDirector::sharedDirector()->getWinSize()
float length = enemy->getContentSize().height + designResolutionSize.height;//飞行距离,超出屏幕即结束
float velocity = 10/1;//飞行速度:420pixel/sec
float realMoveDuration = length/enemy->getSpeed();//飞行时间

CCFiniteTimeAction* actionMove = CCMoveTo::create(realMoveDuration,ccp(x, -enemy->getContentSize().height));
CCFiniteTimeAction* actionDone = CCCallFuncN::create(this,callfuncN_selector(EnemyLayer::EnemyMoveToFinish));//回调一个敌机结束处理函数

CCSequence* sequence = CCSequence::create(actionMove,actionDone,NULL);

enemy->runAction(sequence);

}

}

void EnemyLayer::bomb(CCNode* pSender)
{

CCAnimation *animationBomb = NULL;
Enemy *enemy = (Enemy*) pSender;
char bombMusciName[64];

if (enemy->getType() == bigPlane)
{
sprintf(bombMusciName, "music/enemy3_down.wav");
animationBomb = CCAnimationCache::sharedAnimationCache()->animationByName("animation_Enemy3Bomb");
}
else if(enemy->getType() == midPlane)
{
sprintf(bombMusciName, "music/enemy2_down.wav");
animationBomb = CCAnimationCache::sharedAnimationCache()->animationByName("animation_Enemy2Bomb");
}
else if(enemy->getType() == smallPlane)
{
sprintf(bombMusciName, "music/enemy1_down.wav");
animationBomb = CCAnimationCache::sharedAnimationCache()->animationByName("animation_Enemy1Bomb");
}

SimpleAudioEngine::sharedEngine()->playEffect(bombMusciName, false);//开始播放背景音效,false表示不循环

CCActionInterval *action = CCScaleTo::create(0.5f, pSender->getScale() + 0.05f);
CCCallFuncND *funcND = CCCallFuncND::create(this,callfuncND_selector(EnemyLayer::removeEnemy),(void*)pSender);
CCFiniteTimeAction* seq = CCSequence::create(CCAnimate::create(animationBomb), funcND, NULL);

pSender->stopAllActions();
pSender->runAction(seq);

}


View Code
可以看得出,这两个方法其实放到Enemy类里也很正常完全没问题的,这个要看coder想怎么写了。另外,敌机飞出屏幕外时的删除和被子弹打中时爆炸的回收是不同,差一个爆炸效果,而子弹在这两种情况的处理是一样的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: