Cocos2d-x 3.6 项目实战---贪吃蛇(3)

再说说程序运行的第一个界面,也很简单,只有一个背景和一个Start菜单和一个Help菜单而已,界面如下:
Cocos2d-x 3.6 项目实战---贪吃蛇(3)_第1张图片
MainMenu.h:

#ifndef __snakegame__MainMenu__
#define __snakegame__MainMenu__

#include "cocos2d.h"
USING_NS_CC;
class MainMenu :public Layer{
public:
    static Scene * createScene();
    CREATE_FUNC(MainMenu);
    virtual bool init();
    void menuCallBack(Ref * object);
};
#endif /* defined(__snakegame__MainMenu__) */

MainMenu.cpp:

#include "MainMenu.h"
#include "GameScene.h"
#include "HelpScene.h"

Scene * MainMenu::createScene()
{
    auto scene = Scene::create();
    auto layer = MainMenu::create();
    scene->addChild(layer);
    return scene;
}

bool MainMenu::init()
{
    if (!Layer::init()){
        return false;
    }
    auto size = Director::getInstance()->getWinSize();
    //添加背景
    auto spriteBK = Sprite::create("menuback.png");
    spriteBK->setPosition(Point(size.width / 2, size.height / 2));
    this->addChild(spriteBK);
    //添加2个菜单条目
    auto menuItemStart = MenuItemFont::create("Start", CC_CALLBACK_1(MainMenu::menuCallBack, this));
    menuItemStart->setTag(1);
    auto menuItemHelp = MenuItemFont::create("Help", CC_CALLBACK_1(MainMenu::menuCallBack, this));
    menuItemHelp->setTag(2);
    auto menu = Menu::create(menuItemStart, menuItemHelp, NULL);
    menu->setPosition(Point::ZERO);
    menuItemStart->setPosition(Point(size.width - menuItemStart->getContentSize().width - 100, menuItemStart->getContentSize().height + 10));
    menuItemHelp->setPosition(Point(size.width - menuItemHelp->getContentSize().width - 10, menuItemHelp->getContentSize().height + 10));
    this->addChild(menu);
    return true;
}
//根据tag表示那个菜单被点击了,并切换相应的场景
void MainMenu::menuCallBack(Ref * object){
    auto target = (Node *)object;
    Scene * scene;
    switch (target->getTag()) {
        case 1://startgame
        scene = Game::createScene();
        break;
        case 2://Helpgame
        scene = Help::createScene();
        break;
        default:
        break;
    }
    Director::getInstance()->replaceScene(scene);
}

你可能感兴趣的:(cocos2d-x,项目实战)