cocos2dx 官方示例学习(一), 了解demo结构

如果你是cocos2dx beta 版的, 官方给的demo就在 cocos2d-x-3.0beta\build 中

打开cocos2d-win32.vc2012.sln

找到TextCpp项目 展开Classes

该TextCpp分2场景, 第一个场景就是主界面 要你选择测试的案例, 第二个场景就是测试案例的界面

AppDelegate 程序就是从这里开始的

controller 这就是程序的第一个场景, 即主界面

testBasic 这是第二个场景的基类,所有的测试案例界面都是基于这个场景的子类场景

BaseTest 这是第二个场景中的层的基类,所有的测试案例界场景都会调用基于这个层的子类层

tests.h 这是资源地址

VisibleRect 是用来方便设置坐标的类


我们先来看下AppDelegate.cpp中的代码

//找到下面这段上面的都先不管
    auto scene = Scene::create();//创建一个场景
    auto layer = new TestController();//创建一个层
    layer->autorelease();//放入自动回收池中

    scene->addChild(layer);//把层放入场景中
    director->runWithScene(scene);//跑该场景

然后找到主界面类controller.h

#ifndef _CONTROLLER_H_
#define _CONTROLLER_H_

#include "cocos2d.h"

USING_NS_CC;

class TestController : public Layer
{
public:
    TestController();
    ~TestController();

	//菜单回调函数
    void menuCallback(Object * sender);

	//关闭按钮回调函数
    void closeCallback(Object * sender);

	//触摸开始回调函数
    bool onTouchBegan(Touch* touches, Event  *event);

	//触摸移动回调函数
    void onTouchMoved(Touch* touches, Event  *event);

	//鼠标滚动回调函数
    void onMouseScroll(Event *event);

private:
    Point _beginPos;
    Menu* _itemMenu;
};

#endif

看看如何初始化该类的

TestController::TestController()
: _beginPos(Point::ZERO)
{
    // add close menu
    auto closeItem = MenuItemImage::create(s_pathClose/*正常的图片*/, s_pathClose/*按下去的图片*/, CC_CALLBACK_1(TestController::closeCallback, this)/*触发的函数*/ );
    auto menu =Menu::create(closeItem, NULL);//好似一个MenuItemImage集合

    menu->setPosition( Point::ZERO );
    closeItem->setPosition(Point( /*自定义的窗口类*/VisibleRect::right().x - 30, VisibleRect::top().y - 30));

    // add menu items for tests 添加文字项菜单 用于测试
    _itemMenu = Menu::create();
    for (int i = 0; i < g_testCount; ++i)
    {
// #if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE)
//         auto label = LabelBMFont::create(g_aTestNames[i].c_str(),  "fonts/arial16.fnt");
// #else
        auto label = LabelTTF::create( g_aTestNames[i].test_name, "Arial", 24);
// #endif        
        auto menuItem = MenuItemLabel::create(label, CC_CALLBACK_1(TestController::menuCallback, this));

        _itemMenu->addChild(menuItem, i + 10000);
        menuItem->setPosition( Point( VisibleRect::center().x, (VisibleRect::top().y - (i + 1) * LINE_SPACE) ));
    }

	//设置itemMenu容器的大小 以便于拉动
    _itemMenu->setContentSize(Size(VisibleRect::getVisibleRect().size.width, (g_testCount + 1) * (LINE_SPACE)));
    _itemMenu->setPosition(s_tCurPos);
    addChild(_itemMenu);

    addChild(menu, 1);

    // Register Touch Event 注册触摸监听事件
    auto listener = EventListenerTouchOneByOne::create();
    listener->setSwallowTouches(true);
    
	//回调函数
    listener->onTouchBegan = CC_CALLBACK_2(TestController::onTouchBegan, this);
    listener->onTouchMoved = CC_CALLBACK_2(TestController::onTouchMoved, this);
    
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

	//鼠标滚动事件
    auto mouseListener = EventListenerMouse::create();
    mouseListener->onMouseScroll = CC_CALLBACK_1(TestController::onMouseScroll, this);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this);
}

TestController::~TestController()
{
}

void TestController::menuCallback(Object * sender)
{
	//净化缓存, 包括纹理缓存, 精灵缓存和字体缓存
	Director::getInstance()->purgeCachedData();

    // get the userdata, it's the index of the menu item clicked
	//传进来的 sender 为点击的Menuitem
    auto menuItem = static_cast(sender);
    int idx = menuItem->getZOrder() - 10000;

    // create the test scene and run it
	//创建场景
    auto scene = g_aTestNames[idx].callback();

    if (scene)
    {
		//运行场景
        scene->runThisTest();
        scene->release();
    }
}

testBasic基类的主要功能就是创建一个返回的按钮

void TestScene::onEnter()
{
    Scene::onEnter();

    //add the menu item for back to main menu
//#if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE)
//    auto label = LabelBMFont::create("MainMenu",  "fonts/arial16.fnt");
//#else
	//返回按钮
    auto label = LabelTTF::create("MainMenu", "Arial", 20);
//#endif
    auto menuItem = MenuItemLabel::create(label, testScene_callback );
    auto menu = Menu::create(menuItem, NULL);

    menu->setPosition( Point::ZERO );
    menuItem->setPosition( Point( VisibleRect::right().x - 50, VisibleRect::bottom().y + 25) );

    addChild(menu, 1);
}


让我们看看BaseTest都做了什么

//
//  BaseTest.h
//  TestCpp
//
//  Created by Ricardo Quesada on 6/6/13.
//
//

#ifndef __TestCpp__BaseTest__
#define __TestCpp__BaseTest__

#include "cocos2d.h"

class BaseTest : public cocos2d::Layer
{
public:

	//标题
    virtual std::string title() const;

	//副标题
    virtual std::string subtitle() const;

	//重新开始
	virtual void restartCallback(Object* sender);

	//下一个
	virtual void nextCallback(Object* sender);

	//上一个
	virtual void backCallback(Object* sender);

	//进入
    virtual void onEnter() override;

	//退出
    virtual void onExit() override;
};


#endif /* defined(__TestCpp__BaseTest__) */

//
//  BaseTest.cpp
//  TestCpp
//
//  Created by Ricardo Quesada on 6/6/13.
//
//

#include "BaseTest.h"
#include "VisibleRect.h"
#include "testResource.h"


USING_NS_CC;

void BaseTest::onEnter()
{
	Layer::onEnter();

	// add title and subtitle 创建标题
    std::string str = title();
    const char * pTitle = str.c_str();
    auto label = LabelTTF::create(pTitle, "Arial", 32);
    addChild(label, 9999);
    label->setPosition( Point(VisibleRect::center().x, VisibleRect::top().y - 30) );

    std::string strSubtitle = subtitle();
    if( ! strSubtitle.empty() )
    {
        auto l = LabelTTF::create(strSubtitle.c_str(), "Thonburi", 16);
        addChild(l, 9999);
        l->setPosition( Point(VisibleRect::center().x, VisibleRect::top().y - 60) );
    }

    // add menu 创建几个按钮
	// CC_CALLBACK_1 == std::bind( function_ptr, instance, std::placeholders::_1, ...)
    auto item1 = MenuItemImage::create(s_pathB1, s_pathB2, CC_CALLBACK_1(BaseTest::backCallback, this) );
    auto item2 = MenuItemImage::create(s_pathR1, s_pathR2, CC_CALLBACK_1(BaseTest::restartCallback, this) );
    auto item3 = MenuItemImage::create(s_pathF1, s_pathF2, CC_CALLBACK_1(BaseTest::nextCallback, this) );

    auto menu = Menu::create(item1, item2, item3, NULL);

    menu->setPosition(Point::ZERO);
    item1->setPosition(Point(VisibleRect::center().x - item2->getContentSize().width*2, VisibleRect::bottom().y+item2->getContentSize().height/2));
    item2->setPosition(Point(VisibleRect::center().x, VisibleRect::bottom().y+item2->getContentSize().height/2));
    item3->setPosition(Point(VisibleRect::center().x + item2->getContentSize().width*2, VisibleRect::bottom().y+item2->getContentSize().height/2));

    addChild(menu, 9999);

}

void BaseTest::onExit()
{
	Layer::onExit();
}

//等待重写
std::string BaseTest::title() const
{
	return "";
}

//等待重写
std::string BaseTest::subtitle() const
{
	return "";
}

//等待重写
void BaseTest::restartCallback(Object* sender)
{
	log("override restart!");
}

//等待重写
void BaseTest::nextCallback(Object* sender)
{
	log("override next!");
}

//等待重写
void BaseTest::backCallback(Object* sender)
{
	log("override back!");
}
这是测试层的基类,所以有很多函数定义需要之后补充

我们随便打开一个测试类比如UnitTest.h

#ifndef __UNIT_TEST__
#define __UNIT_TEST__

#include "../testBasic.h"
#include "../BaseTest.h"

class UnitTestScene : public TestScene
{
public:
    virtual void runThisTest() override;
};

class UnitTestDemo : public BaseTest
{
public:
    virtual void onEnter() override;
    virtual void onExit() override;

    virtual std::string title() const override;
    virtual std::string subtitle() const override;

    virtual void restartCallback(Object* sender) override;
    virtual void nextCallback(Object* sender) override;
    virtual void backCallback(Object* sender) override;
};

//-------------------------------------

class TemplateVectorTest : public UnitTestDemo
{
public:
    CREATE_FUNC(TemplateVectorTest);
    virtual void onEnter() override;
    virtual std::string subtitle() const override;
    void constFunc(const Vector& vec) const;
};

class TemplateMapTest : public UnitTestDemo
{
public:
    CREATE_FUNC(TemplateMapTest);
    virtual void onEnter() override;
    virtual std::string subtitle() const override;
    void constFunc(const Map& map) const;
};

class ValueTest : public UnitTestDemo
{
public:
    CREATE_FUNC(ValueTest);
    virtual void onEnter() override;
    virtual std::string subtitle() const override;
    void constFunc(const Value& value) const;
};

#endif /* __UNIT_TEST__ */
该类的场景继承基类场景,层继承基类的层 并重写了基类层的函数


而这些测试类在哪里被调用呢  是在controller类中

struct {
	//名字
	const char *test_name;
	//场景指针
	std::function callback;
} g_aTestNames[] = {

    //
    // TESTS MUST BE ORDERED ALPHABETICALLY
    //     violators will be prosecuted
    //
    { "AUnitTest", []() { return new UnitTestScene(); }},
    { "ANewRenderTest", []() { return new NewRendererTestScene(); } },
	{ "Accelerometer", []() { return new AccelerometerTestScene(); } },
	{ "ActionManagerTest", [](){return new ActionManagerTestScene(); } },
	{ "ActionsEaseTest", [](){return new ActionsEaseTestScene();} },
	{ "ActionsProgressTest", [](){return new ProgressActionsTestScene(); } },
	{ "ActionsTest", [](){ return new ActionsTestScene(); } },
	{ "Box2dTest", []() { return new Box2DTestScene(); } },
	{ "Box2dTestBed", []() { return new Box2dTestBedScene(); } },
	{ "BugsTest", []() { return new BugsTestScene(); } },
#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE)
	{ "ChipmunkTest", []() { return new ChipmunkAccelTouchTestScene(); } },
#endif
	{ "ClickAndMoveTest", [](){return new ClickAndMoveTestScene(); } },
#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE)
	{ "ClippingNodeTest", []() { return new ClippingNodeTestScene(); } },
#endif
	{ "CocosDenshionTest", []() { return new CocosDenshionTestScene(); } },
	{ "ConfigurationTest", []() { return new ConfigurationTestScene(); } },
	{ "ConsoleTest", []() { return new ConsoleTestScene(); } },
#if (CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN)
#if (CC_TARGET_PLATFORM != CC_PLATFORM_NACL)
#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE)
#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA)
	{ "CurlTest", []() { return new CurlTestScene(); } },
#endif
#endif
#endif
#endif
	{ "CurrentLanguageTest", []() { return new CurrentLanguageTestScene(); } },
	{ "DrawPrimitivesTest", [](){return new DrawPrimitivesTestScene();} },
    { "EventDispatcherTest(NEW)", []() { return new EventDispatcherTestScene(); } },
	{ "EffectAdvancedTest", []() { return new EffectAdvanceScene(); } },
	{ "EffectsTest", [](){return new EffectTestScene();} },
	{ "ExtensionsTest", []() { return new ExtensionsTestScene(); } },
	{ "FileUtilsTest", []() { return new FileUtilsTestScene(); } },
	{ "FontTest", []() { return new FontTestScene(); } },
	{ "IntervalTest", [](){return new IntervalTestScene(); } },
	{ "KeyboardTest", []() { return new KeyboardTestScene(); } },
#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA)
	{ "KeypadTest", []() { return new KeypadTestScene(); } },
#endif
	{ "LabelTest", [](){return new AtlasTestScene(); } },
    { "LabelTestNew", [](){return new AtlasTestSceneNew(); } },
	{ "LayerTest", [](){return new LayerTestScene();} },
	{ "MenuTest", [](){return new MenuTestScene();} },
	{ "MotionStreakTest", [](){return new MotionStreakTestScene();} },
    { "MouseTest", []() { return new MouseTestScene(); } },
	{ "MutiTouchTest", []() { return new MutiTouchTestScene(); } },
	{ "NodeTest", [](){return new CocosNodeTestScene();} },
	{ "ParallaxTest", [](){return new ParallaxTestScene(); } },
	{ "ParticleTest", [](){return new ParticleTestScene(); } },
	{ "PerformanceTest", []() { return new PerformanceTestScene(); } },
	{ "PhysicsTest", []() { return new PhysicsTestScene(); } },
	{ "RenderTextureTest", [](){return new RenderTextureScene(); } },
	{ "RotateWorldTest", [](){return new RotateWorldTestScene(); } },
	{ "SceneTest", [](){return new SceneTestScene();} },
	{ "SchedulerTest", [](){return new SchedulerTestScene(); } },
	{ "ShaderTest", []() { return new ShaderTestScene(); } },
    { "ShaderTestSprite", []() { return new ShaderTestScene2(); } },
	{ "SpineTest", []() { return new SpineTestScene(); } },
	{ "SpriteTest", [](){return new SpriteTestScene(); } },
	{ "TextInputTest", [](){return new TextInputTestScene(); } },
	{ "Texture2DTest", [](){return new TextureTestScene(); } },
#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE)
	{ "TextureCacheTest", []() { return new TextureCacheTestScene(); } },
#endif
	{ "TexturePackerEncryption", []() { return new TextureAtlasEncryptionTestScene(); } },
	{ "TileMapTest", [](){return new TileMapTestScene(); } },
	{ "TouchesTest", [](){return new PongScene();} },
	{ "TransitionsTest", [](){return new TransitionsTestScene();} },
	{ "UserDefaultTest", []() { return new UserDefaultTestScene(); } },
	{ "ZwoptexTest", []() { return new ZwoptexTestScene(); } },
};





你可能感兴趣的:(cocos2dx)