飞行游戏demo

新建工程,planeDemo。

首先是进入游戏的第一屏,主菜单屏。

新建类HMenu.并删除HelloWorldScene。

修改AppDelegate.cpp

boolAppDelegate::applicationDidFinishLaunching(),让它首先加载HMenu类。

// create a scene. it's an autorelease object

   CCScene *pScene =HMenu::scene();


    // run

    pDirector->runWithScene(pScene);


将游戏调整为竖屏。

修改RootViewController.mm

*/

// Override to allow orientations other than the default portrait orientation.

// This method is deprecated on ios6

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

   // return UIInterfaceOrientationIsLandscape( interfaceOrientation );

    returnUIInterfaceOrientationIsPortrait(interfaceOrientation);

}


// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead

//- (NSUInteger) supportedInterfaceOrientations{

//#ifdef __IPHONE_6_0

//    return UIInterfaceOrientationMaskLandscape;

//#endif

//}


HMenu添加背景图片

CCSize size=CCDirector::sharedDirector()->getWinSize();

    

    //创建menu背景

   CCSprite *menuBg=CCSprite::create("menu_bg.png");

    menuBg->setPosition(ccp(size.width*0.5,size.height*0.5));

   addChild(menuBg);


添加背景音乐

SimpleAudioEngine::sharedEngine()->playBackgroundMusic("menuMusic.mp3",true);


添加菜单项

//创建菜单项

   CCMenuItem *itemPlay=CCMenuItemImage::create("play_nor.png","play_pre.png",this,menu_selector(HMenu::playIsPressed));

    

   CCMenuItem *itemScore=CCMenuItemImage::create("score_nor.png","score_pre.png",this,menu_selector(HMenu::scoreIsPressed));

    itemScore->setPosition(ccp(0, -itemScore->getContentSize().height-20));

    

   CCMenuItem *itemAbout=CCMenuItemImage::create("about_nor.png","about_pre.png",this,menu_selector(HMenu::aboutIsPressed));

    itemAbout->setPosition(ccp(0, -itemScore->getContentSize().height*2-40));

    

    

   CCMenu *menu=CCMenu::create(itemPlay,itemScore,itemAbout,NULL);

   addChild(menu);


新建类HAbout

//

//  HAbout.h

//  planeDemo

//

//  Created by cloud on 13-4-12.

//

//


#ifndef __planeDemo__HAbout__

#define __planeDemo__HAbout__


#include "cocos2d.h"

class HAbout:publiccocos2d::CCLayer

{

    // Method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer)

   virtualbool init();

public:

    // there's no 'id' in cpp, so we recommend to return the class instance pointer

   staticcocos2d::CCScene* scene();

    

    // preprocessor macro for "static create()" constructor ( node() deprecated )

    CREATE_FUNC(HAbout);

   void returnToMainMenu();

    

};


#endif /* defined(__planeDemo__HAbout__) */


//

//  HAbout.cpp

//  planeDemo

//

//  Created by cloud on 13-4-12.

//

//


#include "HAbout.h"

#include "HMenu.h"

#include "SimpleAudioEngine.h"

using namespace cocos2d;

using namespace CocosDenshion;

CCScene* HAbout::scene()

{

    // 'scene' is an autorelease object

   CCScene *scene =CCScene::create();

    

    // 'layer' is an autorelease object

   HAbout *layer =HAbout::create();

    

    // add layer as a child to scene

    scene->addChild(layer);

    

    // return the scene

   return scene;

}


boolHAbout::init()

{

    //////////////////////////////

    // 1. super init first

   if ( !CCLayer::init() )

    {

        return false;

    }

    CCSize size=CCDirector::sharedDirector()->getWinSize();

    

    //创建menu背景

   CCSprite *menuBg=CCSprite::create("about_bg.png");

    menuBg->setPosition(ccp(size.width*0.5,size.height*0.5));

   addChild(menuBg);

    

    //播放背景音乐

    SimpleAudioEngine::sharedEngine()->playBackgroundMusic("menuMusic.mp3",true);

    

    //创建菜单项

    CCLabelTTF *ttback=CCLabelTTF::create("返回主主菜单","Helvetica-Bold",23);

    ttback->setColor(ccc3(255,255,0));

    

   CCMenuItemLabel *itemReturn=CCMenuItemLabel::create(ttback,this,menu_selector(HAbout::returnToMainMenu));

    itemReturn->setPosition(ccp(0, -200));

        

    

   CCMenu *menu=CCMenu::create(itemReturn,NULL);

   addChild(menu);

    return true;

}


voidHAbout::returnToMainMenu()

{

    CCDirector::sharedDirector()->replaceScene(CCTransitionPageTurn::create(1.5,HMenu::scene(),true));

}

新建类HScore

//

//  HScore.h

//  planeDemo

//

//  Created by cloud on 13-4-12.

//

//


#ifndef __planeDemo__HScore__

#define __planeDemo__HScore__


#include <iostream>

#include "cocos2d.h"

class HScore:publiccocos2d::CCLayer

{

    // Method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer)

   virtualbool init();

public:

    // there's no 'id' in cpp, so we recommend to return the class instance pointer

   staticcocos2d::CCScene* scene();

    

    // preprocessor macro for "static create()" constructor ( node() deprecated )

    CREATE_FUNC(HScore);

   void returnToMainMenu();

    

};

#endif /* defined(__planeDemo__HScore__) */


//

//  HScore.cpp

//  planeDemo

//

//  Created by cloud on 13-4-12.

//

//


#include "HScore.h"

#include "HAbout.h"

#include "HMenu.h"

#include "SimpleAudioEngine.h"

using namespace cocos2d;

using namespace CocosDenshion;

CCScene* HScore::scene()

{

    // 'scene' is an autorelease object

   CCScene *scene =CCScene::create();

    

    // 'layer' is an autorelease object

   HScore *layer =HScore::create();

    

    // add layer as a child to scene

    scene->addChild(layer);

    

    // return the scene

   return scene;

}


boolHScore::init()

{

    //////////////////////////////

    // 1. super init first

   if ( !CCLayer::init() )

    {

        return false;

    }

    CCSize size=CCDirector::sharedDirector()->getWinSize();

    

    //创建menu背景

   CCSprite *menuBg=CCSprite::create("score_bg.png");

    menuBg->setPosition(ccp(size.width*0.5,size.height*0.5));

   addChild(menuBg);

   

    //添加一个文本获取存储的积分

   std::string scoreStr="";

    std::string score=CCUserDefault::sharedUserDefault()->getStringForKey("user_score","-1").c_str();

   if (atoi(score.c_str())!=-1) {

        scoreStr+=score;

    }

   else

    {

        scoreStr="0";

    }

    //显示分数

   CCLabelTTF *ttScore=CCLabelTTF::create(scoreStr.c_str(),"Helvetica",23);

    ttScore->setPosition(ccp(size.width*0.5-50,size.height*0.5+40));

    ttScore->setColor(ccc3(255,0,0));

   addChild(ttScore);

    

    

    

    //创建菜单项

    CCLabelTTF *ttback=CCLabelTTF::create("返回主主菜单","Helvetica-Bold",23);

    ttback->setColor(ccc3(255,255,0));

    

   CCMenuItemLabel *itemReturn=CCMenuItemLabel::create(ttback,this,menu_selector(HScore::returnToMainMenu));

    itemReturn->setPosition(ccp(0, -200));

    

    

   CCMenu *menu=CCMenu::create(itemReturn,NULL);

   addChild(menu);

    return true;

}


voidHScore::returnToMainMenu()

{

    CCDirector::sharedDirector()->replaceScene(CCTransitionFlipX::create(1.5,HMenu::scene()));

}

新建类HWorld,这个是游戏的主类。

新建类HMap,这个类来处理游戏中的地图显示。

//

//  HMap.h

//  planeDemo

//

//  Created by cloud on 13-4-12.

//

//


#ifndef __planeDemo__HMap__

#define __planeDemo__HMap__


#include "cocos2d.h"

typedef enum{

    tag_oneImg,

    tag_twoImg,

}tagMap;

class HMap:publiccocos2d::CCLayer

{

public:

   //实例化函数

   staticHMap *createMap(constchar* fileName);

    

private:

    //初始化

   void mapInit(constchar* fileName);

   //逻辑

   void update(float time);

    //生命周期函数的退出

   virtualvoid onExit();

    

    

};


#endif /* defined(__planeDemo__HMap__) */


//

//  HMap.cpp

//  planeDemo

//

//  Created by cloud on 13-4-12.

//

//


#include "HMap.h"


using namespace cocos2d;

//实例化函数

HMap *HMap::createMap(constchar* fileName)

{

   HMap *map=newHMap();

   if (map && map->create()) {

        map->autorelease();

        map->mapInit(fileName);

       return map;

    }

    CC_SAFE_DELETE(map);

    return NULL;

}

//初始化

voidHMap::mapInit(constchar* fileName)

{

    CCSize size=CCDirector::sharedDirector()->getWinSize();

    //创建第一张地图背景

   CCSprite *turnImg=CCSprite::create(fileName);

    turnImg->setPosition(ccp(turnImg->getContentSize().width*0.5,turnImg->getContentSize().height*0.5));

   this->addChild(turnImg,0,tag_oneImg);

    

    //创建第二张地图背景,用于交替循环

   CCSprite *turnImg2=CCSprite::create(fileName);

    turnImg2->setPosition(ccp(turnImg->getContentSize().width*0.5,turnImg->getContentSize().height*1.5));

   this->addChild(turnImg2,0,tag_twoImg);


   //更新

    this->scheduleUpdate();

    

    

    

}

//逻辑

voidHMap::update(float time)

{

    CCSize size=CCDirector::sharedDirector()->getWinSize();

    CCSprite *sp1=(CCSprite*)this->getChildByTag(tag_oneImg);

    //当第一张图超出屏幕外,将其重置坐标,接在当前显示的图片下

   if (sp1->getPositionY()<=-sp1->getContentSize().height*0.5)

    {

        sp1->setPosition(ccp(sp1->getContentSize().width*0.5,sp1->getContentSize().height*1.5f));

    }

   else

    {

        sp1->setPosition(ccpAdd(sp1->getPosition(),ccp(0,-1)));

    }

                  

    CCSprite *sp2=(CCSprite*)this->getChildByTag(tag_twoImg);

    //当第二张图超出屏幕外,将其重置坐标,接在当前显示的图片下

   if (sp2->getPositionY()<=-sp2->getContentSize().height*0.5)

    {       

        sp2->setPosition(ccp(sp2->getContentSize().width*0.5,sp2->getContentSize().height*1.5f));

    }

   else

    {

        sp2->setPosition(ccpAdd(sp2->getPosition(),ccp(0,-1)));

    }

        

}

//生命周期函数的退出

voidHMap::onExit()

{

    //解除更新

    this->unscheduleUpdate();

   CCLayer::onExit();

}


在HWorld中使用

//添加地图

   HMap *map=HMap::createMap("map.png");

   addChild(map);

//添加音乐

    SimpleAudioEngine::sharedEngine()->playBackgroundMusic("gameMusic.mp3",true);

添加新类主角HPlayer

//

//  HPlayer.h

//  planeDemo

//

//  Created by cloud on 13-4-12.

//

//


#ifndef __planeDemo__HPlayer__

#define __planeDemo__HPlayer__


#include "cocos2d.h"

#include <sstream>

using namespace std;

using namespace cocos2d;

template<typename T>

string Conver2String(const T &value)

{

    stringstream ss;

    ss<<value;

   return ss.str();

}

class HPlayer: public CCSprite,publicCCTouchDelegate

{

public:

   static HPlayer *createPlayer(constchar* fileName);

   void downHp();//掉血

   void addScore(float _value);//加分

   void addKillCount(float _value);//加杀敌数

   bool isDead;//是否死亡

    

    

private:

   int strongTime;//无敌时间

   bool isStrong; //是否处于无敌时间

   int strongCount;//无敌时的计数器

   void strongIng();//处理无敌时的闪烁

   int hp;//血量

   int hpMax;//血量最大值

   int score;//分数

   int killCount;//杀敌数

    

    

   void playerInit();

    //生命周期相关函数

   virtual void onEnter();

   virtual void onExit();

    

   virtual bool ccTouchBegan(CCTouch *pTouch,CCEvent *pEvent);

   virtual void ccTouchMoved(CCTouch *pTouch,CCEvent *pEvent);

   virtual void ccTouchEnded(CCTouch *pTouch,CCEvent *pEvent);

};

#endif /* defined(__planeDemo__HPlayer__) */


//

//  HPlayer.cpp

//  planeDemo

//

//  Created by cloud on 13-4-12.

//

//

#include "HWorld.h"

#include "HPlayer.h"

HPlayer *HPlayer::createPlayer(constchar* fileName)

{

   HPlayer *player=newHPlayer();

   if (player && player->initWithFile(fileName)) {

        player->autorelease();

        player->playerInit();

       return player;

    }

    CC_SAFE_DELETE(player);

    return NULL;

}

voidHPlayer::playerInit()

{

    CCSize size=CCDirector::sharedDirector()->getWinSize();

    //初始化主角位置

    this->setPosition(ccp(size.width*0.5,this->getContentSize().height*0.5));

    

    //血及分数    

    hpMax=3;//初始化血量上限为3

    hp=3;   //初始化当前血量为3

    score=0;//初始化当前积分分数

    strongTime=2*60//初始化无敌时间2

    

    //初始化3个血,加入到Layer

   for (int i=0; i<3; i++)

    {

       CCSprite *spHp=CCSprite::create("icon_hp.png");

        spHp->setPosition(ccp(size.width-this->getContentSize().width*0.5*i-20,spHp->getContentSize().height*0.5));

       if (i==0)

        {

            spHp->setTag(tag_playerHp1);

        }

       else if(i==1)

        {

            spHp->setTag(tag_playerHp2);

        }

       else if(i==2)

        {

            spHp->setTag(tag_playerHp3);

        }

       HWorld::sharedWorld()->addChild(spHp,10);

    }

    //初始化分数文字加入layer

   CCLabelTTF *label=CCLabelTTF::create("分数:","Helvetica-Blod", 24);

    label->setPosition(ccp(35,size.height-22));

   HWorld::sharedWorld()->addChild(label,10);

    

   string strScore=Conver2String(score);

   CCLabelTTF* labelScores=CCLabelTTF::create(strScore.c_str(),"Helvetica-Blod", 24);

    labelScores->setPosition(ccp(110, size.height-22));

    labelScores->setColor(ccc3(255,255, 0));

    HWorld::sharedWorld()->addChild(labelScores,10,tag_scoreTTF);   

    

    

    //杀敌人数

   CCLabelTTF *labelKill=CCLabelTTF::create("杀敌:","Helvetica-Blod", 24);

    labelKill->setPosition(ccp(35,size.height-52));

   HWorld::sharedWorld()->addChild(labelKill,10);

    

   string strKillCount=Conver2String(killCount);

    strKillCount+="/100";

   CCLabelTTF* labelKillCount=CCLabelTTF::create(strKillCount.c_str(),"Helvetica-Blod", 24);

    labelKillCount->setPosition(ccp(110, size.height-52));

    labelKillCount->setColor(ccc3(255,255, 0));

    HWorld::sharedWorld()->addChild(labelKillCount,10,tag_killsCountTTF);

    

    

}

    

voidHPlayer::downHp()

{

   if (isStrong) {

       return;

    }

   hp-=1;

   if (hp<=0) {

       this->setVisible(false);

       isDead=true;

        

       //存储分数

       int oldScore=atoi(CCUserDefault::sharedUserDefault()->getStringForKey("user_score","-1").c_str());

       if (score>oldScore) {

            CCUserDefault::sharedUserDefault()->setStringForKey("user_score",Conver2String(score));

        }

       //调用失败界面

        HWorld::sharedWorld()->lostGame();

    }

   else

    {

       switch (hp) {

           case 1:

                HWorld::sharedWorld()->removeChildByTag(tag_playerHp2,true);

               break;

           case 2:

                HWorld::sharedWorld()->removeChildByTag(tag_playerHp3,true);

               break;

           default:

               break;

        }

    }

    //主角无敌时间

    isStrong=true;

    strongCount=0;

    schedule(schedule_selector(HPlayer::strongIng));

}

voidHPlayer::strongIng()

{

    strongCount++;

    if (strongCount%strongTime==0) {

       this->setVisible(true);

       isStrong=false;

        this->unschedule(schedule_selector(HPlayer::strongIng));

    }

   else

    {

       if (strongCount%3==0) {

           this->setVisible(false);

        }

       else

        {

           this->setVisible(true);

        }

    }

}

voidHPlayer::addScore(float _value)

{    

   score+=_value;

   CCLOG("%d",score);

   string strScore=Conver2String(score);

    CCLabelTTF *ttf=(CCLabelTTF*)HWorld::sharedWorld()->getChildByTag(tag_scoreTTF);

    ttf->setString(strScore.c_str());

}

voidHPlayer::addKillCount(float _value)

{

   killCount+=_value;

   string strKillCount=Conver2String(killCount);

    strKillCount+="/100";

    CCLabelTTF *ttf=(CCLabelTTF*)HWorld::sharedWorld()->getChildByTag(tag_killsCountTTF);

    ttf->setString(strKillCount.c_str());

   if (killCount>=100) {

       //存储分数

       int oldSore=atoi(CCUserDefault::sharedUserDefault()->getStringForKey("user_score","-1").c_str());

       if (score>oldSore) {

            CCUserDefault::sharedUserDefault()->setStringForKey("user_score",Conver2String(score));

            CCUserDefault::sharedUserDefault()->flush();

        }

       //调用胜利界面

        HWorld::sharedWorld()->winGame();

    }

}

    

    

    


voidHPlayer::onEnter()

{

    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0, true);

   CCSprite::onEnter();

}

voidHPlayer::onExit()

{

    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);

   CCSprite::onEnter();

}


boolHPlayer::ccTouchBegan(CCTouch *pTouch,CCEvent *pEvent)

{

    this->setPosition(pTouch->getLocation());

    return true;

}

voidHPlayer::ccTouchMoved(CCTouch *pTouch,CCEvent *pEvent)

{

    this->setPosition(pTouch->getLocation());

}

voidHPlayer::ccTouchEnded(CCTouch *pTouch,CCEvent *pEvent)

{

    this->setPosition(pTouch->getLocation());

}

新建敌人类

//

//  HEnemy.h

//  planeDemo

//

//  Created by cloud on 13-4-14.

//

//


#ifndef __planeDemo__HEnemy__

#define __planeDemo__HEnemy__


#include "cocos2d.h"

using namespace std;

using namespace cocos2d;


class HEnemy: publicCCSprite

{

public:

   static HEnemy  *createEnemy(constchar* fileName,int _type);

    //价值多少分

   int scoreValue;

    

    

private:

   

    //初始化

   void enemyInit(constchar*fileName,int _type);

    

    //敌人成动态表现

   void createAnimate(constchar* fileName,int allCount);

    //敌人逻辑

   void update(float time);

    //是否已经运行过了

   bool isActed;

    //当前敌人类型

   int type;

};

#endif /* defined(__planeDemo__HEnemy__) */

//

//  HEnemy.cpp

//  planeDemo

//

//  Created by cloud on 13-4-14.

//

//

#include "HWorld.h"

#include "HEnemy.h"

HEnemy  *HEnemy::createEnemy(constchar* fileName,int _type)

{

   HEnemy *enemy=newHEnemy();

   if (enemy &&enemy->initWithFile(fileName))

    {

        enemy->autorelease();

        enemy->enemyInit(fileName, _type);

       return enemy;        

    }

    CC_SAFE_DELETE(enemy);

    return NULL;

}

voidHEnemy::enemyInit(constchar*fileName,int _type)

{

   type=_type;

   createAnimate(fileName, 10);

    CCSize size=CCDirector::sharedDirector()->getWinSize();

   if (_type==0) {

       scoreValue=198;

    }

   else if(_type==1)

    {

       scoreValue=428;

    }

   else if(_type==2)

    {

       scoreValue=908;

    }

    //X在屏幕内随机位置

   this->setPosition(ccp(CCRANDOM_0_1()*size.width, size.height+this->getContentSize().height));

    //敌人逻辑

    this->scheduleUpdate();

}

//敌人逻辑

voidHEnemy::update(float time)

{

   switch (type) {

       case 0:

           this->setPosition(ccpAdd(this->getPosition(),ccp(0,-3)));

           break;

       case 1:

        {

            //判断防止重复调用此动作,保证此逻辑只会执行一次

           if (isActed) {

               break;

            }

           isActed=true;

            this->runAction(CCSequence::create(CCMoveTo::create(0.8,HWorld::sharedWorld()->getPlayer()->getPosition()),

                                              CCDelayTime::create(0.5),

                                              CCMoveTo::create(0.8,this->getPosition()),NULL));

        }

           break;

       case 2:

        {

           if (isActed) {

               break;

            }

           isActed=true;

            this->runAction(CCSequence::create(CCMoveTo::create(0.6,HWorld::sharedWorld()->getPlayer()->getPosition()),

                                              CCDelayTime::create(1),

                                              CCMoveTo::create(0.8,this->getPosition()),NULL));            

        }

           break;

       default:

           break;

    }

    if (this->getPositionY()<-this->getContentSize().height) {

       //

        HWorld::sharedWorld()->getArrayForEnemy()->removeObject(this);

        //从父类删除当前子弹

        this->getParent()->removeChild(this,true);

    }

   HPlayer *player=HWorld::sharedWorld()->getPlayer();

   if (!player->isDead) {

        if (player->boundingBox().intersectsRect(this->boundingBox()))

        {

            player->downHp();

        }

    }

    

}

//敌人成动态表现

voidHEnemy::createAnimate(constchar* fileName,int allCount)

{

    CCAnimation *animation=CCAnimation::create();

   CCTexture2D *texture=CCTextureCache::sharedTextureCache()->addImage(fileName);

   int eachWidth=this->getContentSize().width/allCount;

   for (int i=0; i<allCount; i++) {

        animation->addSpriteFrameWithTexture(texture,CCRectMake(i*eachWidth, 0, eachWidth, this->getContentSize().height));

    }

    animation->setDelayPerUnit(0.03f);

    animation->setRestoreOriginalFrame(true);

    animation->setLoops(-1);

   CCFiniteTimeAction *animate=CCAnimate::create(animation);

   this->runAction(animate);

    

}


新建子弹类

//

//  HBullet.h

//  planeDemo

//

//  Created by cloud on 13-4-15.

//

//


#ifndef __planeDemo__HBullet__

#define __planeDemo__HBullet__


#include "cocos2d.h"

using namespace cocos2d;


class HBullet:publicCCSprite

{

public:

   static HBullet *createBullet(constchar* _fileName,float _speed,CCPoint _position);

private:

   void bulletInit(float _speed,CCPoint _position);

   void update(float time);

   float speed;

    

   virtual void onExit();

};


#endif /* defined(__planeDemo__HBullet__) */

//

//  HBullet.cpp

//  planeDemo

//

//  Created by cloud on 13-4-15.

//

//

#include "HEnemy.h"

#include "HWorld.h"

#include "HBullet.h"

#include "SimpleAudioEngine.h"

#include "HPlayer.h"

using namespace CocosDenshion;

HBullet *HBullet::createBullet(constchar* _fileName,float _speed,CCPoint _position)

{

   HBullet *bullet=newHBullet();

   if (bullet &&bullet->initWithFile(_fileName)) {

        bullet->autorelease();

        bullet->bulletInit(_speed, _position);

       return bullet;

    }

    CC_SAFE_DELETE(bullet);

    return NULL;

}


voidHBullet::bulletInit(float _speed,CCPoint _position)

{

   speed=_speed;

   this->setPosition(_position);

    this->scheduleUpdate();

}

voidHBullet::update(float time)

{

    //子弹向上运动

    this->setPosition(ccpAdd(this->getPosition(),ccp(0,speed)));

    CCArray *array=HWorld::sharedWorld()->getArrayForEnemy();

   for (int i=0; i<array->count(); i++) {

       HEnemy *enemy=(HEnemy *)array->objectAtIndex(i);

        if (enemy->boundingBox().intersectsRect(this->boundingBox()))

        {

           //爆炸音效

            SimpleAudioEngine::sharedEngine()->playEffect("effect_boom.mp3");

            

           //爆炸粒子效果

           CCParticleSystemQuad *particle=

            CCParticleSystemQuad::create("particle_boom.plist");

            particle->setPosition(enemy->getPosition());

            particle->setAutoRemoveOnFinish(true);

           HWorld::sharedWorld()->addChild(particle);

            

           //增加分数

           HWorld::sharedWorld()->getPlayer()->addScore(enemy->scoreValue);

           //添加杀人数

            HWorld::sharedWorld()->getPlayer()->addKillCount(1);

            //从敌人数组将被攻击的敌怪删除

            array->removeObject(enemy);

           //删除子弹与敌怪

           HWorld::sharedWorld()->removeChild(enemy,true);

           HWorld::sharedWorld()->removeChild(this,true);

        }

    }

    CCSize size=CCDirector::sharedDirector()->getWinSize();

   if (this->getPositionY()>size.height) {

        HWorld::sharedWorld()->removeChild(this,true);

    }

}


voidHBullet::onExit()

{

    this->unscheduleUpdate();

   CCSprite::onExit();

}

修改World类

//

//  HWorld.cpp

//  planeDemo

//

//  Created by cloud on 13-4-12.

//

//


#include "HWorld.h"

#include "HScore.h"

#include "HAbout.h"

#include "HMenu.h"

#include "HMap.h"

#include "HPlayer.h"

#include "SimpleAudioEngine.h"

#include "HEnemy.h"

#include "HBullet.h"

using namespace cocos2d;

using namespace CocosDenshion;

staticHWorld *sh;

HPlayer *HWorld::getPlayer()

{

    HPlayer *player=(HPlayer*)HWorld::sharedWorld()->getChildByTag(tag_player);

   return player;

}

HWorld *HWorld::sharedWorld()

{

   if (sh!=NULL) {

       return sh;

    }

    return NULL;

}

CCScene* HWorld::scene()

{

    // 'scene' is an autorelease object

   CCScene *scene = CCScene::create();

    

    // 'layer' is an autorelease object

   HWorld *layer = HWorld::create();

    

    // add layer as a child to scene

    scene->addChild(layer);

    

    // return the scene

   return scene;

}


boolHWorld::init()

{

    //////////////////////////////

    // 1. super init first

   if ( !CCLayer::init() )

    {

        return false;

    }

   sh=this;

    

    //添加地图

   HMap *map=HMap::createMap("map.png");

   addChild(map);

    //添加音乐

    SimpleAudioEngine::sharedEngine()->playBackgroundMusic("gameMusic.mp3",true);

    

   //主角

   HPlayer *player=HPlayer::createPlayer("player.png");

   addChild(player,0,tag_player);      

    

    //敌怪数组

    arrayEnemy=CCArray::create();

    CC_SAFE_RETAIN(arrayEnemy);

        

    //创建子弹逻辑

    this->schedule(schedule_selector(HWorld::autoCreateBullet),0.37);

    

    //创建敌怪逻辑(创建间隔1秒)

    this->schedule(schedule_selector(HWorld::autoCreateEnemy),1);


    return true;

}

voidHWorld::autoCreateEnemy()

{

   int randomCount=CCRANDOM_0_1()*10;//随机本次创建enemy的个数

   for (int i=0; i<randomCount; i++) {

       int random=CCRANDOM_0_1()*10;

       HEnemy *enemy=NULL;

       int randomType=CCRANDOM_0_1()*10;

        

       //随机怪的贴图

       const char* name;

       if(random>=0 && random<=2)

        {

            name="enemy_bug.png";

        }

       else if(random>=3 && random<=6)

        {

            name="enemy_duck.png";

        }

       else if(random>=7 && random<=10)

        {

            name="enemy_pig.png";

        }

        

       //随机类型

       if (randomType%2==0) {

            randomType=0;

        }

       else

        {

            randomType=1;

        }

        enemy=HEnemy::createEnemy(name,randomType);

       arrayEnemy->addObject(enemy);

       addChild(enemy);

        

    }

}

voidHWorld::winGame()

{

    //添加胜利界面

    CCSize size=CCDirector::sharedDirector()->getWinSize();

   CCLayerColor *layer=CCLayerColor::create(ccc4(0,0, 0, 190),size.width,size.height);

    CCSprite *sp=CCSprite::create("game_win.png");

    sp->setPosition(ccp(size.width*0.5,size.height*0.5));

    layer->addChild(sp);

   addChild(layer,100);

    

    //添加一个按钮用于返回menu

    CCLabelTTF *ttback=CCLabelTTF::create("返回主菜单","Helvetica-Bold", 23);

    CCMenuItemLabel *menuLabel=CCMenuItemLabel::create(ttback,this,menu_selector(HWorld::backMenu));

    menuLabel->setPosition(ccp(0, -200));

   CCMenu *menu=CCMenu::create(menuLabel,NULL);

   addChild(menu,100);

    

    //暂停游戏

    CCDirector::sharedDirector()->pause();

    

}

voidHWorld::lostGame()

{

    //添加失败界面

    CCSize size=CCDirector::sharedDirector()->getWinSize();

   CCLayerColor *layer=CCLayerColor::create(ccc4(0,0, 0, 190),size.width,size.height);

    CCSprite *sp=CCSprite::create("game_lost.png");

    sp->setPosition(ccp(size.width*0.5,size.height*0.5));

    layer->addChild(sp);

   addChild(layer,100);

    

    //添加一个按钮用于返回menu

    CCLabelTTF *ttback=CCLabelTTF::create("返回主菜单","Helvetica-Bold", 23);

    CCMenuItemLabel *menuLabel=CCMenuItemLabel::create(ttback,this,menu_selector(HWorld::backMenu));

    menuLabel->setPosition(ccp(0, -200));

   CCMenu *menu=CCMenu::create(menuLabel,NULL);

   addChild(menu,100);

    

    //暂停游戏

    CCDirector::sharedDirector()->pause();

}

voidHWorld::backMenu()

{

    this->unscheduleAllSelectors();

    //继续游戏

    CCDirector::sharedDirector()->resume();

    //切换到"菜单"场景

    CCDirector::sharedDirector()->replaceScene(HMenu::scene());

}

voidHWorld::autoCreateBullet()

{

    //主角子弹

    HPlayer *player=(HPlayer*)this->getChildByTag(tag_player);

    this->addChild(HBullet::createBullet("p_bullet.png",2, ccpAdd(player->getPosition(),ccp(0,player->getContentSize().height*0.5))));

    //子弹音效

    SimpleAudioEngine::sharedEngine()->playEffect("effect_bullet.mp3");

}

CCArray *HWorld::getArrayForEnemy()

{

    returnarrayEnemy;

}

HWorld::~HWorld()//析构函数

{

    CC_SAFE_RELEASE(arrayEnemy);

}


源码地址:http://download.csdn.net/detail/cloud95/5262590

你可能感兴趣的:(飞行游戏demo)