1. 程式人生 > >Cocos2d-x 3.2 簡易飛機大戰教程系列 【一】

Cocos2d-x 3.2 簡易飛機大戰教程系列 【一】

本系列為原創,為簡易版飛機大戰,實現功能有限。提前宣告,只為自己和各位初學者提供幫助!奮鬥

【一】滾動背景實現

首先,我們要知道,遊戲中的飛機飛行,背景的移動,其實都是背景圖片的滾動,兩張相同的背景圖片不停的向下滑動,讓我們看起來就像是飛機在向上飛行一樣。所以,我們可以寫一個函式來實現背景圖片的滾動效果。

接下來,明白原理之後,我們當然要準備兩張一樣的背景圖片,然後建立一個新類 BackGround,寫入以下程式碼:

BackGround.h:

#include "cocos2d.h"
USING_NS_CC;
class BackGround:public Node
{
public:
    static Scene * createScene();
    CREATE_FUNC(BackGround);
    bool init();
    void MoveBackGround(float t);
};

BackGround.cpp:
#include "BackGround.h"
bool BackGround::init()
{
    if(!Node::init())
    {
        return false;
    }
    //獲取螢幕大小
    Size winSize = Director::getInstance()->getWinSize();
    char buff[15];
    //定義一個隨機數在1~5之間取值
    int id=(int)CCRANDOM_0_1() *(5-1+1)+1;
    //將取到的值存入字串buff中
    sprintf(buff,"img_bg_%d.jpg",id);
    //建立背景圖片
    //建立隨機圖片是為了以後可能要修改使用,也可以直接用一張圖片來當背景圖片 原理是相同的
//    Sprite *background=Sprite::create("gamebg.jpg");
    
    Sprite *background=Sprite::create(buff);
    background->setTag(10);
    background->setAnchorPoint(Vec2(0,0));
    background->setPosition(0,0);
    this->addChild(background);
    
    //建立相同圖片的背景
//    Sprite *background2=Sprite::create("gamebg.jpg");
    
    Sprite *background2=Sprite::create(buff);
    background2->setAnchorPoint(Vec2(0,0));
    background2->setPosition(0,background->getContentSize().height);
    background2->setTag(100);
    this->addChild(background2);
    
    //定義計時器,逐幀呼叫方法
    this->schedule(schedule_selector(BackGround::MoveBackGround),1/60.0f);
    return true;
    
}
void BackGround::MoveBackGround(float t)
{
    //移動背景圖片,已達到背景移動的效果
    auto sp=this->getChildByTag(10);
    auto sp2=this->getChildByTag(100);
    sp->setPositionY(sp->getPositionY()-1);
    if(sp->getPositionY()<=-1136)
    {
        sp->setPositionY(0);
    }
    //設定背景圖片2在背景圖片1最上方
    sp2->setPositionY(sp->getPositionY()+sp->getContentSize().height);
}

到這裡 背景圖片的函式已經寫完,接下來,我們要在GameScene類中把背景創建出來,程式碼如下:

在GameScene的init()方法中 使用 BackGround類 create一個物件,然後新增到Scene中

bool GameScene::init()
{
    if(!Layer::init())
    {
        return false;
    }
    BackGround *background=BackGround::create();
    this->addChild(background);
    return true;
}
到此,關於滾動背景的教程到此結束~

新增一個動態效果圖: