zoukankan      html  css  js  c++  java
  • cocos2d-x的TestCpp分析

    最近,我刚开始学coco2d-x 我会写我的学习经验来 首先TestCppproject有许多例子文件夹,而在这些文件夹以外的其他文件 。我首先研究这些文件:
    controller.h/cpp:管理方案,所有演示样品菜单      
    AppDelegate.h/cpp:程序控制类
    tests.h:实例总头文件       
    testBasic.h/cpp:演示样例场景基类
    testResource.h:文件资源名称
    VisibleRect.h/cpp:屏幕大小
    接下来我将一一分析以上的文件
    1.AppDelegate.h/cpp:       

    AppDelegate.h       

    class  AppDelegate : private cocos2d::CCApplication
    {
    public:
        AppDelegate();
        virtual ~AppDelegate();
        virtual bool applicationDidFinishLaunching();//实现CCDirector和CCScene的初始化。假设失败则终止
        virtual void applicationDidEnterBackground();//函数被调用时。应用进入后台
        virtual void applicationWillEnterForeground();//函数被调用是,应用显示在前台
    };
    AppDelegate.cpp  

    #include "AppDelegate.h"
    
    #include "cocos2d.h"
    #include "controller.h"
    #include "SimpleAudioEngine.h"
    #include "cocos-ext.h"
    
    USING_NS_CC;
    using namespace CocosDenshion;
    
    AppDelegate::AppDelegate()
    {
    }
    
    AppDelegate::~AppDelegate()
    {
    //    SimpleAudioEngine::end();
    	cocos2d::extension::CCArmatureDataManager::purge();//清空数据
    }
    
    bool AppDelegate::applicationDidFinishLaunching()
    {
    	// As an example, load config file
    	// XXX: This should be loaded before the Director is initialized,
    	// XXX: but at this point, the director is already initialized
    	CCConfiguration::sharedConfiguration()->loadConfigFile("configs/config-example.plist");//载入配置文件
    
        // initialize director
        CCDirector *pDirector = CCDirector::sharedDirector();//获得导演对象
        pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());//设置OpenGL视窗
    
        CCSize screenSize = CCEGLView::sharedOpenGLView()->getFrameSize();//获取屏幕大小
    
        CCSize designSize = CCSizeMake(480, 320);//设置设计分辨率大小
    
        CCFileUtils* pFileUtils = CCFileUtils::sharedFileUtils();//使用文件资源
        std::vector<std::string> searchPaths;//声明一个string类型的向量
        
    	if (screenSize.height > 320) //下面都是设置屏幕分辨率。这个是高分辨率
        {
            CCSize resourceSize = CCSizeMake(960, 640);//设置资源分辨率大小 
            searchPaths.push_back("hd");
    		searchPaths.push_back("hd/scenetest");
            pDirector->setContentScaleFactor(resourceSize.height/designSize.height);//设置屏幕比例系数
        }
    	else//低分辨率
    	{
    		searchPaths.push_back("scenetest");
    	}
    	pFileUtils->setSearchPaths(searchPaths);
    
     #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
        CCEGLView::sharedOpenGLView()->setDesignResolutionSize(designSize.width, designSize.height, kResolutionShowAll);
    #else
    	CCEGLView::sharedOpenGLView()->setDesignResolutionSize(designSize.width, designSize.height, kResolutionNoBorder);
    #endif
    
        CCScene * pScene = CCScene::create();//创建场景
        CCLayer * pLayer = new TestController();//创建层
        pLayer->autorelease();//使用内存管理器自己主动回收
    
        pScene->addChild(pLayer);//将层加入进场景中
        pDirector->runWithScene(pScene);//执行创建的场景
    
        return true;
    }
    
    // This function will be called when the app is inactive. When comes a phone call,it's be invoked too
    void AppDelegate::applicationDidEnterBackground()//当应用进入后台是被调用
    {
        CCDirector::sharedDirector()->stopAnimation();
        SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
        SimpleAudioEngine::sharedEngine()->pauseAllEffects();
    }
    
    // this function will be called when the app is active again
    void AppDelegate::applicationWillEnterForeground()//应用显示在前台
    {
        CCDirector::sharedDirector()->startAnimation();
        SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
        SimpleAudioEngine::sharedEngine()->resumeAllEffects();
    }
    2.testBase.h/cpp  
    testBase.h:

    #ifndef _TEST_BASIC_H_
    #define _TEST_BASIC_H_
    
    #include "cocos2d.h"
    #include "VisibleRect.h"
    
    USING_NS_CC;
    using namespace std;
    
    class TestScene : public CCScene
    {
    public: 
        TestScene(bool bPortrait = false);//设置标志是否实例化TestScene
        virtual void onEnter();//场景被载入时被调用
    
        virtual void runThisTest() = 0;//用于执行场景
    
        // The CallBack for back to the main menu scene
        virtual void MainMenuCallback(CCObject* pSender);//回调MainMenuCallback()返回主界面
    };
    
    typedef CCLayer* (*NEWTESTFUNC)();//定义NEWTESTFUNC()指针函数为CCLayer
    #define TESTLAYER_CREATE_FUNC(className)       //定义定义createclassName()函数为TESTAYER_CREATE_FUNC
    static CCLayer* create##className() 		//返回className()
    { return new className(); }
    
    #define CF(className) create##className         //定义createclassName为CF(classname)
    
    #endif
    testBase.cpp


    #include "testBasic.h"
    #include "controller.h"
    
    TestScene::TestScene(bool bPortrait)//构造函数
    {
        
        CCScene::init();
    }
    
    void TestScene::onEnter()//场景载入时的函数
    {
        CCScene::onEnter();
    
        //add the menu item for back to main menu
    //#if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE)
    //    CCLabelBMFont* label = CCLabelBMFont::create("MainMenu",  "fonts/arial16.fnt");
    //#else
        CCLabelTTF* label = CCLabelTTF::create("MainMenu", "Arial", 20);//显示一个文字标签
    //#endif
        CCMenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, this, menu_selector(TestScene::MainMenuCallback));  //添加一个菜单标签 并添加了回调函数
    
        CCMenu* pMenu =CCMenu::create(pMenuItem, NULL);//将菜单标签添加菜单中
    
        pMenu->setPosition( CCPointZero );
        pMenuItem->setPosition( ccp( VisibleRect::right().x - 50, VisibleRect::bottom().y + 25) );
    
        addChild(pMenu, 1);               //将菜单添加场景中
    }
    
    void TestScene::MainMenuCallback(CCObject* pSender)
    {
        CCScene* pScene = CCScene::create();     //新创建一个场景
        CCLayer* pLayer = new TestController();//实例化一个主菜单的层
        pLayer->autorelease();
    
        pScene->addChild(pLayer);
        CCDirector::sharedDirector()->replaceScene(pScene);//用主菜单的场景和层用以替换之前的场景
    }
    


    3.controller.h/cpp
    controller.h
    #ifndef _CONTROLLER_H_
    #define _CONTROLLER_H_
    
    #include "cocos2d.h"
    
    USING_NS_CC;
    
    class TestController : public CCLayer
    {
    public:
        TestController();
        ~TestController();
    
        void menuCallback(CCObject * pSender);          //菜单项响应回调函数
        void closeCallback(CCObject * pSender);         //关闭程序回调函数
    
        virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent);//按下触点响应函数
        virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent);//按下状态移动触点响应函数
    
    private:
        CCPoint m_tBeginPos;//按下状态移动触点的開始位置
        CCMenu* m_pItemMenu;//主菜单
    };
    
    #endif

    controller.cpp

    #include "controller.h"
    #include "testResource.h"
    #include "tests.h"
    
    #define LINE_SPACE          40//菜单项的行间距
    
    static CCPoint s_tCurPos = CCPointZero;//触点位置变量,初始化为左下角位置
    
    static TestScene* CreateTestScene(int nIdx)//创建演示样例的场景
    {
        CCDirector::sharedDirector()->purgeCachedData();//清除缓存数据
    
        TestScene* pScene = NULL;//定义TestScene指针用于接收创建的演示样例场景
    
        switch (nIdx)        //依据索引来创建对应的演示样例场景
        {
        case TEST_ACTIONS:
             pScene = new ActionsTestScene(); break;//动画处理
        case TEST_TRANSITIONS:
    	 pScene = new TransitionsTestScene(); break;//场景切换
     case TEST_PROGRESS_ACTIONS: pScene = new ProgressActionsTestScene(); break;//进度动画
     case TEST_EFFECTS: pScene = new EffectTestScene(); break;//特效 
     case TEST_CLICK_AND_MOVE: pScene = new ClickAndMoveTestScene(); break;//拖动測试
     case TEST_ROTATE_WORLD: pScene = new RotateWorldTestScene(); break;//旋转
     case TEST_PARTICLE: pScene = new ParticleTestScene(); break;//粒子系统 
     case TEST_EASE_ACTIONS: pScene = new ActionsEaseTestScene(); break;//多样化
     case TEST_MOTION_STREAK: pScene = new MotionStreakTestScene(); break;//拖尾动画
     case TEST_DRAW_PRIMITIVES: pScene = new DrawPrimitivesTestScene(); break;//基本图形 
     case TEST_COCOSNODE: pScene = new CocosNodeTestScene(); break;//节点
     case TEST_TOUCHES: pScene = new PongScene(); break;//触屏
     case TEST_MENU: pScene = new MenuTestScene(); break;//菜单 
     case TEST_ACTION_MANAGER: pScene = new ActionManagerTestScene(); break;//动画管理
     case TEST_LAYER: pScene = new LayerTestScene(); break;//层測试
     case TEST_SCENE: pScene = new SceneTestScene(); break;//场景測试 
     case TEST_PARALLAX: pScene = new ParallaxTestScene(); break;//视角測试
     case TEST_TILE_MAP: pScene = new TileMapTestScene(); break;//瓦片地图
     case TEST_INTERVAL: pScene = new IntervalTestScene(); break;//时间 
     case TEST_LABEL: pScene = new AtlasTestScene(); break;//文字标签
     case TEST_TEXT_INPUT: pScene = new TextInputTestScene(); break;//文本输入
     case TEST_SPRITE: pScene = new SpriteTestScene(); break;//精灵
     case TEST_SCHEDULER: pScene = new SchedulerTestScene(); break;//预处理器
     case TEST_RENDERTEXTURE: pScene = new RenderTextureScene(); break;//渲染纹理 
     case TEST_TEXTURE2D: pScene = new TextureTestScene(); break;//纹理
     #if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) 
     case TEST_CHIPMUNK: pScene = new ChipmunkAccelTouchTestScene(); break;
     #endif
     case TEST_BOX2D: pScene = new Box2DTestScene(); break;//Box2D物理引擎 
     case TEST_BOX2DBED: pScene = new Box2dTestBedScene(); break;//物体的固定于连接
     case TEST_EFFECT_ADVANCE: pScene = new EffectAdvanceScene(); break;//高级效果
     case TEST_ACCELEROMRTER: pScene = new AccelerometerTestScene(); break;//加速计
     #if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA)
     case TEST_KEYPAD: pScene = new KeypadTestScene(); break;//键盘处理
     #endif
     case TEST_COCOSDENSHION: pScene = new CocosDenshionTestScene(); break;//声效控制
     case TEST_PERFORMANCE: pScene = new PerformanceTestScene(); break;//性能測试
     case TEST_ZWOPTEX: pScene = new ZwoptexTestScene(); break;// bada don't support libcurl
     #if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA && CC_TARGET_PLATFORM != CC_PLATFORM_NACL && CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE && CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN)
     case TEST_CURL:#if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8)
     pScene = new CurlTestScene(); break;//网络通信
     #else CCMessageBox("CurlTest not yet implemented.","Alert"); break;
     #endif
     #endif
     case TEST_USERDEFAULT: pScene = new UserDefaultTestScene(); break;//用户日志保存 
     case TEST_BUGS: pScene = new BugsTestScene(); break;//Bug演示样例
     case TEST_FONTS: pScene = new FontTestScene(); break;//字体
     case TEST_CURRENT_LANGUAGE: 
     pScene = new CurrentLanguageTestScene(); break;//当前语言
     #if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE)
     case TEST_TEXTURECACHE: pScene = new TextureCacheTestScene(); break;
     #endif 
     case TEST_EXTENSIONS: pScene = new ExtensionsTestScene(); break; 
     case TEST_SHADER:
     #if (CC_TARGET_PLATFORM != CC_PLATFORM_WP8)
     pScene = new ShaderTestScene();//着色器
     #else
     CCMessageBox("ShaderTest not yet implemented.","Alert");
     #endif break; case TEST_MUTITOUCH: pScene = new MutiTouchTestScene();//多点触控 
     break;#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE)
     case TEST_CLIPPINGNODE: pScene = new ClippingNodeTestScene(); break;
     #endif 
     case TEST_FILEUTILS:
     pScene = new FileUtilsTestScene(); break; 
     case TEST_SPINE:
     pScene = new SpineTestScene(); break; 
     case TEST_TEXTUREPACKER_ENCRYPTION:
     pScene = new TextureAtlasEncryptionTestScene(); break;
     case TEST_DATAVISTOR:
     pScene = new DataVisitorTestScene(); break;
     case TEST_CONFIGURATION:pScene = new ConfigurationTestScene();break;
     default: break; 
     }
     return pScene;
     }
     TestController::TestController()//构造函数用于初始化场景
     : m_tBeginPos(CCPointZero)
     {				//加入了一个关闭菜单按钮回调closeCallback()函数
    
     CCMenuItemImage *pCloseItem = CCMenuItemImage::create(s_pPathClose, s_pPathClose, this, menu_selector(TestController::closeCallback) );
     CCMenu* pMenu =CCMenu::create(pCloseItem, NULL);//将关闭项加入到主菜单
     pMenu->setPosition( CCPointZero );//设置菜单位置
     pCloseItem->setPosition(ccp( VisibleRect::right().x - 30, VisibleRect::top().y - 30)); // add menu items for tests
     m_pItemMenu = CCMenu::create(); //新建菜单项,全部演示样例都在这里
     for (int i = 0; i < TESTS_COUNT; ++i)
     {
     // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE)
     // CCLabelBMFont* label = CCLabelBMFont::create(g_aTestNames[i].c_str(), "fonts/arial16.fnt");
     //#else
     CCLabelTTF* label = CCLabelTTF::create(g_aTestNames[i].c_str(), "Arial", 24);//将字符串转换为字符常量//
     #endif
     CCMenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, this, menu_selector(TestController::menuCallback));
     m_pItemMenu->addChild(pMenuItem, i + 10000);//将菜单项加入主菜单。以i+10000为Z轴 
     pMenuItem->setPosition( ccp( VisibleRect::center().x, (VisibleRect::top().y - (i + 1) * LINE_SPACE) )); } 
     m_pItemMenu->setContentSize(CCSizeMake(VisibleRect::getVisibleRect().size.width, (TESTS_COUNT + 1) * (LINE_SPACE))); //总共的演示样例菜单尺寸
     m_pItemMenu->setPosition(s_tCurPos); addChild(m_pItemMenu);//加入演示样例菜单 setTouchEnabled(true);//开启触屏 addChild(pMenu, 1);//加入关闭项
     }
     TestController::~TestController(){}
     void TestController::menuCallback(CCObject * pSender){ 
     // get the userdata, it's the index of the menu item clicked 
     CCMenuItem* pMenuItem = (CCMenuItem *)(pSender); int nIdx = pMenuItem->getZOrder() - 10000;//得出当前的演示样例菜单项索引 
     // create the test scene and run it
     TestScene* pScene = CreateTestScene(nIdx);//创建菜单
     if (pScene)//假设激活了当前场景
     {
     pScene->runThisTest();//执行当前场景
     pScene->release(); }}
     void TestController::closeCallback(CCObject * pSender){
     #if(CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
     #else
     CCDirector::sharedDirector()->end();//退出程序
     #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
     exit(0);
     #endif
     #endif
     }
     void TestController::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)//触点按下时的响应
    { CCSetIterator it = pTouches->begin(); //获取第一个触点位置
    CCTouch* touch = (CCTouch*)(*it);
    m_tBeginPos = touch->getLocation(); //将第一个触点的位置坐标保存到m_tBeginPos中
    }
    void TestController::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent)
    { CCSetIterator it = pTouches->begin();
    CCTouch* touch = (CCTouch*)(*it); 
    CCPoint touchLocation = touch->getLocation(); //获取第一个触点位置的坐标
    float nMoveY = touchLocation.y - m_tBeginPos.y; //取得这个位置与之前的位置的纵坐标上的偏移 
    CCPoint curPos = m_pItemMenu->getPosition(); //当前菜单的位置坐标
    CCPoint nextPos = ccp(curPos.x, curPos.y + nMoveY);//菜单也移动与触点移动一样的偏移量
    if (nextPos.y < 0.0f) { m_pItemMenu->setPosition(CCPointZero); //假设下一点超出了屏幕的坐标范围则菜单项不变
    return;
    }
    if (nextPos.y > ((TESTS_COUNT + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height))
    { m_pItemMenu->setPosition(ccp(0, ((TESTS_COUNT + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height))); 
    return;
    }
    m_pItemMenu->setPosition(nextPos); //更新当前的菜单项的位置
    m_tBeginPos = touchLocation;//更新当前位置坐标
    s_tCurPos = nextPos;}
    
    4.VisibleRect.h/cpp
    VisibleRect.cpp

    #include "VisibleRect.h"               //这个类主要是配合设置屏幕分辨率来用的
    
    CCRect VisibleRect::s_visibleRect;
    
    void VisibleRect::lazyInit()
    {
        if (s_visibleRect.size.width == 0.0f && s_visibleRect.size.height == 0.0f)
        {
            CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();//获取EGLView视图
            s_visibleRect.origin = pEGLView->getVisibleOrigin();//得到视图起点
            s_visibleRect.size = pEGLView->getVisibleSize();    //得到可见矩形尺寸
        }
    }
    
    CCRect VisibleRect::getVisibleRect()          //设置可见矩形的位置尺寸的
    {
        lazyInit();
        return CCRectMake(s_visibleRect.origin.x, s_visibleRect.origin.y, s_visibleRect.size.width, s_visibleRect.size.height);
    }
    
    CCPoint VisibleRect::left()                     //下面是获取可见矩形9点坐标      
    {
        lazyInit();
        return ccp(s_visibleRect.origin.x, s_visibleRect.origin.y+s_visibleRect.size.height/2);
    }
    
    CCPoint VisibleRect::right()
    {
        lazyInit();
        return ccp(s_visibleRect.origin.x+s_visibleRect.size.width, s_visibleRect.origin.y+s_visibleRect.size.height/2);
    }
    
    CCPoint VisibleRect::top()
    {
        lazyInit();
        return ccp(s_visibleRect.origin.x+s_visibleRect.size.width/2, s_visibleRect.origin.y+s_visibleRect.size.height);
    }
    
    CCPoint VisibleRect::bottom()
    {
        lazyInit();
        return ccp(s_visibleRect.origin.x+s_visibleRect.size.width/2, s_visibleRect.origin.y);
    }
    
    CCPoint VisibleRect::center()
    {
        lazyInit();
        return ccp(s_visibleRect.origin.x+s_visibleRect.size.width/2, s_visibleRect.origin.y+s_visibleRect.size.height/2);
    }
    
    CCPoint VisibleRect::leftTop()
    {
        lazyInit();
        return ccp(s_visibleRect.origin.x, s_visibleRect.origin.y+s_visibleRect.size.height);
    }
    
    CCPoint VisibleRect::rightTop()
    {
        lazyInit();
        return ccp(s_visibleRect.origin.x+s_visibleRect.size.width, s_visibleRect.origin.y+s_visibleRect.size.height);
    }
    
    CCPoint VisibleRect::leftBottom()
    {
        lazyInit();
        return s_visibleRect.origin;
    }
    
    CCPoint VisibleRect::rightBottom()
    {
        lazyInit();
        return ccp(s_visibleRect.origin.x+s_visibleRect.size.width, s_visibleRect.origin.y);
    }
    

    最终完成的事情  。 我是个新手  。那里是没有希望的大神指点权, 如果一个问题可能是一个问题,我长线。


  • 相关阅读:
    Lua中的closure、泛型for
    Lua多重继承
    (转)C++ new详解
    C++重载操作符学习
    Lua中使用继承来组装新的环境
    DOS:变量嵌套和命令嵌套
    C++中成员的私有性
    ManualResetEvent 类
    在IIS中部署和注册WCF服务
    ArcGIS Server 10 地图缓存新特性
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4605083.html
Copyright © 2011-2022 走看看