中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

[cocos2d-x]SpaceFighting[安卓/IOS都適用]

發布時間:2020-06-18 00:05:13 來源:網絡 閱讀:442 作者:蓬萊仙羽 欄目:游戲開發

前言:閑來無事找個小游戲項目練練手吧!也供初學者朋友學習和參考,讓我們共同進步!下面我就介紹一下一個類似打飛機游戲的小項目的制作,實現跟微信打飛機一樣的效果!并且成功導入到安卓機上!

項目設計大概思路:

1.游戲的菜單界面的編寫(Play、Score、About)
添加背景音樂->選項場景的創建->設置關閉聲音->游戲測試

2.游戲舞臺屏幕的編寫,背景無限移動

3.飛船類的編寫

4.敵機的編寫

5.×××類以及碰撞檢測的編寫

6.游戲勝利以及失敗場景的編寫

詳細設計:

1.主場景(菜單選項場景)的設計

HMenu.h:

// //  HMenu.h //  dafeiji // //  Created by 丁小未 on 13-9-25. // //  #ifndef __dafeiji__HMenu__ #define __dafeiji__HMenu__  #include <iostream> #include "cocos2d.h"  using namespace cocos2d; class HMenu : public CCLayer { public:     virtual bool init();     static CCScene * scene();     CREATE_FUNC(HMenu); private:     //開始游戲     void playerIsPressed();     //分數顯示     void scoreIsPressed();     //關于作者     void aboutIsPressed(); };  #endif /* defined(__dafeiji__HMenu__) */

HMenu.cpp:

// //  HMenu.cpp //  dafeiji // //  Created by 丁小未 on 13-9-25. // //  #include "HMenu.h" #include "SimpleAudioEngine.h" #include "HScore.h" #include "HAbout.h" #include "HWorld.h" using namespace cocos2d; using namespace CocosDenshion;  CCScene * HMenu::scene() {     CCScene *scene = CCScene::create();     HMenu * layer = HMenu::create();     scene->addChild(layer);     return scene; }  bool HMenu::init() {     if (!CCLayer::init()) {         return false;     }     SimpleAudioEngine::sharedEngine()->playBackgroundMusic("menuMusic", true);          CCSize size = CCDirector::sharedDirector()->getWinSize();          //添加背景精靈     CCSprite *sp = CCSprite::create("menu_bg.png");     sp->setPosition(CCPointMake(size.width/2, size.height/2));     addChild(sp);          //添加三個菜單選項貼圖     CCMenuItemImage *itemPlay = CCMenuItemImage::create("play_nor.png", "play_pre.png",this,menu_selector(HMenu::playerIsPressed));          CCMenuItemImage * itemScore = CCMenuItemImage::create("score_nor.png", "score_pre.png", this, menu_selector(HMenu::scoreIsPressed));     itemScore->setPosition(CCPointMake(0, -itemScore->getContentSize().height - 20));          CCMenuItemImage * itemAbout = CCMenuItemImage::create("about_nor.png", "about_pre.png",this,menu_selector(HMenu::aboutIsPressed));     itemAbout->setPosition(CCPointMake(0, -itemAbout->getContentSize().height*2 - 40));          //添加菜單選項卡     CCMenu *menu = CCMenu::create(itemPlay,itemScore,itemAbout,NULL);     addChild(menu);          return true; }  //進入玩游戲主場景 void HMenu::playerIsPressed() {     CCLog("1");     CCDirector::sharedDirector()->replaceScene(CCTransitionFadeDown::create(1, HWorld::scene())); }  //進入顯示分數場景 void HMenu::scoreIsPressed() {     CCLog("2");     CCDirector::sharedDirector()->replaceScene(CCTransitionCrossFade::create(1, HScore::scene())); }  //進入關于作者場景 void HMenu::aboutIsPressed() {     CCLog("3");     CCDirector::sharedDirector()->replaceScene(CCTransitionCrossFade::create(1, HAbout::scene())); }


2.游戲背景的設計(實現無限滾屏,也就是兩張圖片來回不停切換)

HMap.h:

// //  HMap.h //  dafeiji // //  Created by 丁小未 on 13-9-26. // //  #ifndef __dafeiji__HMap__ #define __dafeiji__HMap__  #include <iostream> #include "cocos2d.h" using namespace cocos2d; typedef enum {     tag_oneImg,     tag_twoImg, }tagMap;  class HMap:public CCLayer { public:     //創建一個map     static HMap* createMap(const char * fileName); private:     void mapInit(const char * fileName);          void update(float time);          virtual void onExit(); };  #endif /* defined(__dafeiji__HMap__) */ 

HMap.cpp:

// //  HMap.cpp //  dafeiji // //  Created by 丁小未 on 13-9-26. // //  #include "HMap.h"  //模仿CREATE_FUNC()函數自己創建一個對象 HMap * HMap::createMap(const char *fileName) {     HMap * map = new HMap();     if (map&&map->create()) {         map->autorelease();         map->mapInit(fileName);         return map;     }     CC_SAFE_DELETE(map);     return NULL; }  void HMap::mapInit(const char *fileName) {     CCSize size = CCDirector::sharedDirector()->getWinSize();          //創建兩張圖片精靈來回切換     CCSprite * turnImg1 = CCSprite::create(fileName);     turnImg1->setPosition(CCPointMake(turnImg1->getContentSize().width/2, turnImg1->getContentSize().height/2));     this->addChild(turnImg1,0,tag_oneImg);          CCSprite * turnImg2 = CCSprite::create(fileName);     turnImg2->setPosition(CCPointMake(turnImg2->getContentSize().width/2, turnImg2->getContentSize().height * 1.5));     this->addChild(turnImg2,0,tag_twoImg);          //啟動定時器來實現兩張背景圖片的循環交叉滾動     this->scheduleUpdate(); }  //自上而下滾屏效果 void HMap::update(float time) {     CCSize size = CCDirector::sharedDirector()->getWinSize();          CCSprite * sp1 = (CCSprite *)this->getChildByTag(tag_oneImg);     //如果第一張背景圖的中點到達屏幕下方背景圖高度的一半的時候(也就是第一張圖片移除圖片下面的時候)重新設置他的位置到屏幕上面,圖片下邊緣跟手機屏幕上邊緣重合-1個像素     if (sp1->getPositionY()<=-sp1->getContentSize().height/2) {         sp1->setPosition(CCPointMake(sp1->getContentSize().width/2, sp1->getContentSize().height*1.5f - 1));     }     //如果還沒需要換位置就讓他向下移動一個像素     else     {         sp1->setPosition(ccpAdd(sp1->getPosition(), ccp(0,-1)));     }          CCSprite * sp2 = (CCSprite *)this->getChildByTag(tag_twoImg);     //如果第二張背景圖移出屏幕最下方則重新設置他的位置在屏幕的最上方     if (sp2->getPositionY()<=-sp2->getContentSize().height/2) {         sp2->setPosition(CCPointMake(sp2->getContentSize().width/2, sp2->getContentSize().height*1.5 - 1));     }     //向下移動     else{         sp2->setPosition(ccpAdd(sp2->getPosition(), ccp(0,-1)));     } }  //如果退出 void HMap::onExit() {     this->unscheduleUpdate();     CCLayer::onExit();//還要調用父類的退出方法 } 


3.主角類的設計:

HPlayer.h:

// //  HPlayer.h //  dafeiji // //  Created by 丁小未 on 13-9-26. // //  #ifndef __dafeiji__HPlayer__ #define __dafeiji__HPlayer__  #include <iostream> #include "cocos2d.h" #include <sstream> using namespace std; //導入C++命名空間 using namespace cocos2d;  //模板,將任意類型轉化成string類型 template <typename T> string Convert2String(const T &value) {     stringstream ss;     ss<<value;     return ss.str(); }  //創建player,具備點擊的精靈 class HPlayer: public CCSprite,public CCTouchDelegate { public:     //創建主角精靈     static HPlayer * createPlayer(const char* fileName);     //當前血量     int hp;     //最大血量     int hpMax;     //分數     int score;     //殺敵數     int killCount;     //掉血     void downHp();     //添加分數     void addScore(float _value);     //添加殺敵數     void addKillCount(float _value);     //判斷是否死亡     bool isDead; //private:     //無敵狀態的時間     int strongTime;     //是否無敵狀態     bool isStrong;     //     int strongCount;     //無敵狀態函數     void strongIng();     //主角精靈初始化     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(__dafeiji__HPlayer__) */ 

HPlayer.cpp:

// //  HPlayer.cpp //  dafeiji // //  Created by 丁小未 on 13-9-26. // //  #include "HPlayer.h" #include "HWorld.h"   using namespace cocos2d;  //創建主角精靈 HPlayer *HPlayer::createPlayer(const char* fileName) {     HPlayer * player=new HPlayer();     //由于繼承自CCSprite,然后調用CCSprite的initWithFile方法     if (player && player->initWithFile(fileName)) {         player->autorelease();         //調用初始化方法         player->playerInit();         return player;     }     CC_SAFE_DELETE(player);     return NULL; }  //設置配置參數,初始化血量,殺敵數等 void HPlayer::playerInit() {     CCSize size=CCDirector::sharedDirector()->getWinSize();     //設置主角的位置在屏幕下面正中央     this->setPosition(ccp(size.width*0.5, this->getContentSize().height*0.5));     //設置參數(血量,當前血量,無敵時間,分數)     hpMax=5;     hp=5;     score=0;     strongTime=2*60;          //添加右下角的血量貼圖     for (int i=0; i<5; i++) {         CCSprite *spHp=CCSprite::create("icon_hp.png");         //設置每個血量貼圖在屏幕的右下角一次排列,并且從右至左tag分別是值為5,4,3,2,1的枚舉類型         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);         }else if(i==3){             spHp->setTag(tag_playerHP4);         }else if(i==4){             spHp->setTag(tag_playerHP5);         }         //將每一個血量貼圖添加到HWorld場景中         HWorld::sharedWorld()->addChild(spHp,10);     }     //添加分數label     CCLabelTTF *label=CCLabelTTF::create("分數", "Helvetica-Blood", 24);     label->setPosition(ccp(30, size.height-22)); //位置左上方     HWorld::sharedWorld()->addChild(label,10);          //分數結果     string strScore=Convert2String(score);     CCLabelTTF * labelScores=CCLabelTTF::create(strScore.c_str(),"Helvetica-Blood",24);     labelScores->setPosition(ccp(110, size.height-22));     labelScores->setColor(ccc3(255, 255, 0)); //設置顏色為×××     HWorld::sharedWorld()->addChild(labelScores,10,tag_scoreTTF);                    //添加殺敵label     CCLabelTTF *labelKill=CCLabelTTF::create("殺敵", "Helvetica-Blood", 24);     labelKill->setPosition(ccp(30, size.height-52));     HWorld::sharedWorld()->addChild(labelKill,10);          //殺敵數     string strKillCount=Convert2String(killCount);     strKillCount+="/100"; //C++中string可以直接拼接     CCLabelTTF *labelKillCount=CCLabelTTF::create(strKillCount.c_str(), "Helvetica-Blood", 24);     labelKillCount->setPosition(ccp(110, size.height-52));     labelKillCount->setColor(ccc3(255, 255, 0)); //設置為×××     HWorld::sharedWorld()->addChild(labelKillCount,10,tag_killsCountTTF); }  //添加分數 void HPlayer::addScore(float _value) {     score+=_value;     string strScore=Convert2String(score);     //根據HWorld獲取場景中分數標簽并且改變他的值     CCLabelTTF *ttf=(CCLabelTTF *)HWorld::sharedWorld()->getChildByTag(tag_scoreTTF);     ttf->setString(strScore.c_str()); }  //添加殺敵數 void HPlayer::addKillCount(float _value) {     killCount+=_value;     string strKillCount=Convert2String(killCount);     strKillCount+="/100";     //獲取HWorld中殺敵數標簽,并且改變他的值     CCLabelTTF *ttf=(CCLabelTTF *)HWorld::sharedWorld()->getChildByTag(tag_killsCountTTF);     ttf->setString(strKillCount.c_str());     //當殺敵過百的時候,游戲勝利     if (killCount>=100) {         //         int oldScore=atoi(CCUserDefault::sharedUserDefault()->getStringForKey("user_score","-1").c_str());//當取出的鍵值為NULL的時候默認為1         if (oldScore!=-1&&score>oldScore) {             CCUserDefault::sharedUserDefault()->setStringForKey("user_score", Convert2String(score));             CCUserDefault::sharedUserDefault()->flush(); //必須要寫,刷新數據         }         //調用勝利界面         HWorld::sharedWorld()->winGame();     } }  //讓主角掉血的方法,分為死亡和飛死亡兩種情況來分析 void HPlayer::downHp() {     //如果還出于無敵狀態則不需要掉血     if (isStrong) {         return;     }     //血量減少1     hp-=1;     //如果血量少于0,則將主角設置不可見并且設置他已經死亡     if (hp<=0) {         this->setVisible(false);         isDead=true;         //取出舊的分數         int oldScore=atoi(CCUserDefault::sharedUserDefault()->getStringForKey("user_score","-1").c_str());         //當有新的分數,就將新的分數保存到數據中,并且要刷新保存         if (oldScore!=-1&&score>oldScore)         {             CCUserDefault::sharedUserDefault()->setStringForKey("user_score", Convert2String(score));             CCUserDefault::sharedUserDefault()->flush();         }         HWorld::sharedWorld()->lostGame();     }     //如果主角還為死亡然后移除相應界面中的血量貼圖     else     {         switch (hp) {             case 1:                 HWorld::sharedWorld()->removeChildByTag(tag_playerHP2, true);                 break;             case 2:                 HWorld::sharedWorld()->removeChildByTag(tag_playerHP3, true);                 break;             case 3:                 HWorld::sharedWorld()->removeChildByTag(tag_playerHP4, true);                 break;             case 4:                 HWorld::sharedWorld()->removeChildByTag(tag_playerHP5, true);                 break;         }         //將無敵狀態開啟,并且開啟無敵狀態的定時器         isStrong=true;         strongCount=0;//無敵狀態的時間         this->schedule(schedule_selector(HPlayer::strongIng));     } }  //正處于無敵狀態中 void HPlayer::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);         }     } }  //當主角精靈初始化的時候注冊他的觸摸事件 void HPlayer::onEnter() {     CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);     CCSprite::onEnter(); //調用父類的onEnter方法,這里是調用的CCNode的onEnter方法 }  //當主角精靈退出的時候取消他的注冊觸摸事件 void HPlayer::onExit() {     CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);     CCSprite::onExit(); }  //設置主角精靈的當前位置 bool HPlayer::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) {     this->setPosition(pTouch->getLocation());     return true; }  //觸摸移動的時候不斷的去移動主角精靈讓他跟隨著鼠標移動而移動 void HPlayer::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) {     this->setPosition(pTouch->getLocation()); }  //觸摸結束 void HPlayer::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) {     this->setPosition(pTouch->getLocation()); }

4.敵人類的設計:

HEnemy.h:

// //  HEenemy.h //  dafeiji // //  Created by 丁小未 on 13-9-26. // //  #ifndef __dafeiji__HEenemy__ #define __dafeiji__HEenemy__  #include <iostream> #include "cocos2d.h" using namespace cocos2d; class HEnemy:public CCSprite { public:     //創建Enemy     static HEnemy* createEnemy(const char *fileName,int _type);     //怪物的值     int scoreValue; private:          void enemyInit(const char * fileName,int _type);          void createAnimate(const char *fileName,int allCount);          void update(float time);          //是否被***了     bool isActed;          int type; }; #endif /* defined(__dafeiji__HEenemy__) */ 

HEnemy.cpp:

// //  HEenemy.cpp //  dafeiji // //  Created by 丁小未 on 13-9-26. // //  #include "HEenemy.h" #include "HWorld.h" using namespace cocos2d; //創建Enemy HEnemy* HEnemy::createEnemy(const char *fileName, int _type) {     HEnemy * enemy = new HEnemy();     if (enemy && enemy->initWithFile(fileName)) {         enemy->autorelease();         enemy->enemyInit(fileName, _type);         return enemy;     }     CC_SAFE_DELETE(enemy);     return NULL; }  void HEnemy::enemyInit(const char *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;     }     this->setPosition(CCPointMake(CCRANDOM_0_1()*size.width, size.height+this->getContentSize().height));     this->scheduleUpdate(); }  void HEnemy::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(1.6, HWorld::sharedWorld()->getPlayer()->getPosition()),CCDelayTime::create(1.0),CCMoveTo::create(1.8, this->getPosition()),NULL));             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();         }     } }  //創建動畫 void HEnemy::createAnimate(const char *fileName, int allCount) {     CCAnimation *animation = CCAnimation::create();     CCTexture2D *texture = CCTextureCache::sharedTextureCache()->addImage(fileName);     int eachWith = this->getContentSize().width/allCount;     for (int i = 0; i<allCount; i++) {         animation->addSpriteFrameWithTexture(texture, CCRectMake(i*eachWith, 0, eachWith, this->getContentSize().height));     }     animation->setDelayPerUnit(0.03f);     animation->setRestoreOriginalFrame(true);     animation->setLoops(-1);     CCFiniteTimeAction *animate = CCAnimate::create(animation);     this->runAction(animate); }  

5.×××類的設計:

HBullet.h:

// //  HBullet.h //  dafeiji // //  Created by 丁小未 on 13-9-26. // //  #ifndef __dafeiji__HBullet__ #define __dafeiji__HBullet__  #include <iostream> #include "cocos2d.h" using namespace cocos2d;  class HBullet:public CCSprite { public:     //創建×××     static HBullet * createBullet(const char *_fileName,float _speed,CCPoint _position); private:     //×××的初始化,供create調用     void bulletInit(float _speed,CCPoint _position);     void update(float time);     float speed;          virtual void onExit(); }; #endif /* defined(__dafeiji__HBullet__) */ 


HBullet.cpp:

// //  HBullet.cpp //  dafeiji // //  Created by 丁小未 on 13-9-26. // //  #include "HBullet.h" #include "HWorld.h" #include "HEenemy.h" #include "SimpleAudioEngine.h"  using namespace CocosDenshion;  HBullet *HBullet::createBullet(const char *_fileName,float _speed, CCPoint _position) {     HBullet *bullet=new HBullet();     if (bullet && bullet->initWithFile(_fileName)) {         bullet->autorelease();         bullet->bulletInit(_speed, _position);         return bullet;     }     CC_SAFE_DELETE(bullet);     return NULL; } //初始化×××的速度以及位置,并且調用×××的update方法 void HBullet::bulletInit(float _speed,CCPoint _position) {     speed=_speed;     this->setPosition(_position);     this->scheduleUpdate(); }  //碰撞檢測 void HBullet::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);             //調用主場景中獲取主角的方法并調用他的addScore方法             HWorld::sharedWorld()->getPlayer()->addScore(enemy->scoreValue);             HWorld::sharedWorld()->getPlayer()->addKillCount(1);             //從數組中移除到當前的敵人             array->removeObject(enemy);             //從界面中移除敵人             HWorld::sharedWorld()->removeChild(enemy, true);             //移除當前的×××類             HWorld::sharedWorld()->removeChild(this, true);         }              }      }  //退出的時候將×××的Update方法取消 void HBullet::onExit() {     this->unscheduleUpdate();     //注意要調用父類的退出方法     CCSprite::onExit(); }


6.游戲Fighting主場景的設計

HWorld.h:

// //  HWorld.h //  dafeiji // //  Created by 丁小未 on 13-9-26. // //  #ifndef __dafeiji__HWorld__ #define __dafeiji__HWorld__  #include <iostream> #include "cocos2d.h" #include "HPlayer.h" typedef enum {     //主角的tag     tag_player,     //5個血量的tag     tag_playerHP1,     tag_playerHP2,     tag_playerHP3,     tag_playerHP4,     tag_playerHP5,     //分數的Label的tag     tag_scoreTTF,     //殺敵數的tag     tag_killsCountTTF, }tagWorld;  using namespace cocos2d; class HWorld : public CCLayer{      public:     static CCScene * scene();     static HWorld * sharedWorld();     //獲取玩家精靈     HPlayer *getPlayer();     //獲取敵人數組     CCArray *getArrayForEnemy();     void lostGame();     void winGame();      private:     virtual bool init();     CREATE_FUNC(HWorld);     virtual ~HWorld();     HWorld();     void backMenu();//返回菜單     CCArray *arrayEnemy;     void autoCreateEnemy();     void autoCreateBullet(); };  #endif /* defined(__dafeiji__HWorld__) */

HWorld.cpp:

// //  HWorld.cpp //  dafeiji // //  Created by 丁小未 on 13-9-26. // //  #include "HWorld.h" #include "SimpleAudioEngine.h" #include "HMap.h" #include "HPlayer.h" #include "HMenu.h" #include "HBullet.h" #include "HEenemy.h"  using namespace CocosDenshion; static HWorld *sh ;  HWorld* HWorld::sharedWorld() {     if (sh!= NULL) {         return sh;     }     return NULL; }  CCScene * HWorld::scene() {     CCScene * scene = CCScene::create();     HWorld * layer = HWorld::create();     scene->addChild(layer);     return scene; }  bool HWorld::init() {     if (!CCLayer::init()) {         return false;     }     //獲取到當前的對象     sh = this;     //播放場景音樂     SimpleAudioEngine::sharedEngine()->playBackgroundMusic("gameMusic.mp3", true);     //添加背景     HMap * map = HMap::createMap("map.png");     addChild(map);          //添加主角精靈     HPlayer * player = HPlayer::createPlayer("player.png");     addChild(player,0,tag_player);          //創建×××     this->schedule(schedule_selector(HWorld::autoCreateBullet),0.3);     //創建敵人     this->schedule(schedule_selector(HWorld::autoCreateEnemy),1);          //創建arrayEnemy     arrayEnemy = CCArray::create();     CC_SAFE_RETAIN(arrayEnemy);               return true;  }  //自動創建不同的敵人 void HWorld::autoCreateEnemy() {     int randomCount=CCRANDOM_0_1()*10;     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);     } }  //自動創建××× void HWorld::autoCreateBullet() {     HPlayer *player=(HPlayer *)this->getChildByTag(tag_player);     this->addChild(HBullet::createBullet("p_bullet.png", 1, ccpAdd(player->getPosition(), ccp(0, player->getContentSize().height*0.5))));     SimpleAudioEngine::sharedEngine()->playEffect("effect_bullet.mp3"); }  //游戲勝利場景 void HWorld::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(CCPointMake(size.width/2, size.height/2));     layer->addChild(sp);     addChild(layer,100);     //添加菜單項     CCLabelTTF * ttback = CCLabelTTF::create("返回主菜單", "Helvetica-Bold", 23);     CCMenuItemLabel *menuLabel = CCMenuItemLabel::create(ttback, this, menu_selector(HWorld::backMenu));     menuLabel->setPosition(CCPointMake(0, -200));          CCMenu * menu = CCMenu::create(menuLabel,NULL);     addChild(menu,100);          //游戲暫停     CCDirector::sharedDirector()->pause();      }  //游戲失敗場景 void HWorld::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(CCPointMake(size.width/2, size.height/2));     //將圖片添加到層中     layer->addChild(sp);     //將層添加到場景中     this->addChild(layer,100);          CCLabelTTF *ttback = CCLabelTTF::create("返回主菜單", "Helvetica-Bold", 23);     CCMenuItemLabel *menuLabel = CCMenuItemLabel::create(ttback, this, menu_selector(HWorld::backMenu));     //菜單選項卡在CCMenu中的坐標系是以屏幕的中點為原點     menuLabel->setPosition(CCPointMake(0, -200));          CCMenu* menu = CCMenu::create(menuLabel,NULL);     addChild(menu,100);          CCDirector::sharedDirector()->pause();      }  //通過tag獲取主角精靈 HPlayer * HWorld::getPlayer() {     HPlayer * player=(HPlayer *)HWorld::sharedWorld()->getChildByTag(tag_player);     return player; }  //返回敵人數組 CCArray * HWorld::getArrayForEnemy() {     return arrayEnemy; } //返回菜單 void HWorld::backMenu() {     this->unscheduleAllSelectors();     CCDirector::sharedDirector()->resume();     CCDirector::sharedDirector()->replaceScene(HMenu::scene()); }  //構造函數 HWorld::HWorld(){}  //析構函數 HWorld::~HWorld() {     //清除敵人數組 }

7.分數場景的設計:

HScore.h:

// //  HScore.h //  dafeiji // //  Created by 丁小未 on 13-9-25. // //  #ifndef __dafeiji__HScore__ #define __dafeiji__HScore__  #include <iostream> #include "cocos2d.h" using namespace cocos2d; class HScore : public CCLayer { public:     virtual bool init();     static CCScene * scene();     CREATE_FUNC(HScore); private:     void backMenu(); }; #endif /* defined(__dafeiji__HScore__) */

HScore.cpp:

// //  HScore.cpp //  dafeiji // //  Created by 丁小未 on 13-9-25. // //  #include "HScore.h" #include "HMenu.h"  using namespace std;  CCScene * HScore::scene() {     CCScene * scene = CCScene::create();     CCLayer * layer = HScore::create();     scene->addChild(layer);     return scene; }  bool HScore::init() {     if (!CCLayer::init()) {         return false;     }          CCSize size = CCDirector::sharedDirector()->getWinSize();          //創建背景     CCSprite * sp = CCSprite::create("score_bg.png");     sp->setPosition(CCPointMake(size.width/2, size.height/2));     addChild(sp);          string scoreStr = "";     string score = CCUserDefault::sharedUserDefault()->getStringForKey("user_score","-1").c_str();//如果沒有值的話就默認為-1     //atoi接受的是一個c風格的字符串返回的是一個×××     //c_str是返回一個C類型的字符串     if (atoi(score.c_str())!=-1) {         scoreStr+=score;     }     else{         scoreStr = "0";     }          //分數     CCLabelTTF * ttfAbout = CCLabelTTF::create(scoreStr.c_str(), "Helvetica", 23);     ttfAbout->setPosition(CCPointMake(size.width * 0.5 - 50, size.height * 0.5 + 40));     ttfAbout->setColor(ccRED);     this->addChild(ttfAbout);          //返回主菜單     CCLabelTTF * ttback = CCLabelTTF::create("返回主菜單","Helvetica", 23);     //設置為×××     ttback->setColor(ccc3(255, 255, 0));          CCMenuItemLabel *menuLabel = CCMenuItemLabel::create(ttback, this, menu_selector(HScore::backMenu));     menuLabel->setPosition(CCPointMake(0, -200));          CCMenu * menu = CCMenu::create(menuLabel,NULL);     addChild(menu);          return true; }  void HScore::backMenu() {     //自上而下翻滾切換     CCDirector::sharedDirector()->replaceScene(CCTransitionFadeDown::create(1.5, HMenu::scene())); }


8.關于作者場景的設計:

HAbout.c:

// //  HAbout.h //  dafeiji // //  Created by 丁小未 on 13-9-25. // //  #ifndef __dafeiji__HAbout__ #define __dafeiji__HAbout__  #include <iostream> #include "cocos2d.h"  using namespace cocos2d;  class HAbout : public CCLayer { public:     virtual bool init();     static CCScene * scene();     CREATE_FUNC(HAbout); private:     void backMenu(); }; #endif /* defined(__dafeiji__HAbout__) */

HAbout.cpp:

// //  HAbout.cpp //  dafeiji // //  Created by 丁小未 on 13-9-25. // //  #include "HAbout.h" #include "HMenu.h" #include "SimpleAudioEngine.h"  using namespace CocosDenshion;  CCScene * HAbout::scene() {     CCScene * scene = CCScene::create();     CCLayer * layer = HAbout::create();     scene->addChild(layer);     return scene; }  bool HAbout::init() {     if (!CCLayer::init()) {         return false;     }          CCSize size = CCDirector::sharedDirector()->getWinSize();     //添加背景     CCSprite * sp = CCSprite::create("score_bg.png");     sp->setPosition(CCPointMake(size.width/2, size.height/2));     addChild(sp);          //添加返回菜單     CCLabelTTF * ttback = CCLabelTTF::create("返回主菜單", "Helvetica-bold", 23);     ttback->setColor(ccc3(255, 255, 0));     //返回菜單項     CCMenuItemLabel * menuLabel = CCMenuItemLabel::create(ttback, this, menu_selector(HAbout::backMenu));     menuLabel->setPosition(CCPointMake(0, -200));          CCMenu *menu = CCMenu::create(menuLabel,NULL);     addChild(menu);          return true; }  //返回主菜單 void HAbout::backMenu() {     //翻頁切換     CCDirector::sharedDirector()->replaceScene(CCTransitionPageTurn::create(1.5, HMenu::scene(), true)); }

運行效果:

[cocos2d-x]SpaceFighting[安卓/IOS都適用][cocos2d-x]SpaceFighting[安卓/IOS都適用][cocos2d-x]SpaceFighting[安卓/IOS都適用][cocos2d-x]SpaceFighting[安卓/IOS都適用][cocos2d-x]SpaceFighting[安卓/IOS都適用]


如何修適應安卓機?

1.在AppDelegate的applicationDidFinishLaunching方法中添加這么一行屏幕分辨率自適應:
CCEGLView::sharedOpenGLView()->setDesignResolutionSize(320,480,kResolutionUnKnown);

2.還有在eclipse中修改一個AndroidManifest.xml文件,
屏幕默認是橫屏的,如果要修改成縱屏,則修改android:screenOrientation="portrait"

項目源碼:http://download.csdn.net/detail/s10141303/6334027

已經編譯成的安卓項目:http://download.csdn.net/detail/s10141303/6422971

或者加群獲得源碼

cocos2d-x游戲開發QQ交流群:280818155

備注:加入者必須修改:地區-昵稱,很少有動態的將定期清理


==================== 迂者 丁小未 CSDN博客專欄=================

MyBlog:http://blog.csdn.net/dingxiaowei2013             MyQQ:1213250243

Unity QQ群:858550         cocos2dx QQ群:280818155

====================== 相互學習,共同進步 ===================

轉載請注明出處:http://blog.csdn.net/dingxiaowei2013/article/details/12111867

歡迎關注我的微博:http://weibo.com/u/2590571922

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

福建省| 新兴县| 嘉荫县| 小金县| 垣曲县| 华亭县| 蓬莱市| 闸北区| 麻江县| 永和县| 石河子市| 新化县| 东城区| 炎陵县| 邢台县| 金溪县| 广宁县| 左贡县| 青岛市| 凤城市| 江都市| 安溪县| 南通市| 孟津县| 平武县| 会同县| 黄冈市| 怀集县| 万年县| 西青区| 青河县| 德州市| 宁都县| 读书| 庆城县| 西昌市| 敦化市| 诸城市| 沧州市| 蒙山县| 二手房|