cocos2d-x C++ 原始工程引擎运行机制解析

新建一个工程,相信感兴趣的同学都想知道cocos引擎都是如何运行的

想知道是如何运行的,看懂四个文件即可

话不多说,上代码:

1、首先解释 AppDelegate.h

 1 #ifndef  _APP_DELEGATE_H_
 2 #define  _APP_DELEGATE_H_
 3
 4 #include "cocos2d.h"
 5
 6 /**
 7 @brief    The cocos2d Application.
 8
 9 Private inheritance here hides part of interface from Director.
10 */  //从这里可以看到AppDelegate继承了cocos2d::Application ,而cocos2d::Application是cocos2d-x引擎提供的基类
11 class  AppDelegate : private cocos2d::Application
12 {
13 public:
14     AppDelegate();
15     virtual ~AppDelegate();
16     /*
17
18      */
19     virtual void initGLContextAttrs();
20
21     /**
22     @brief    Implement Director and Scene init code here.
23     @return true    Initialize success, app continue.
24     @return false   Initialize failed, app terminate.
25         *游戏启动时调用的函数,在这里可以初始化导演对象和场景对象
26     */
27     virtual bool applicationDidFinishLaunching();
28
29     /**
30     @brief  Called when the application moves to the background
31     @param  the pointer of the application
32         *游戏进入后台时调用的函数
33     */
34     virtual void applicationDidEnterBackground();
35
36     /**
37     @brief  Called when the application reenters the foreground
38     @param  the pointer of the application
39         *游戏进入前台时调用的函数
40     */
41     virtual void applicationWillEnterForeground();
42 };
43
44 #endif // _APP_DELEGATE_H_

2、AppDelegate.cpp

#include "AppDelegate.h"
#include "HelloWorldScene.h"

USING_NS_CC;//这个是cocos2d-x提供的一个宏,它是用来替换 using namespace cocos2d语句的。

static cocos2d::Size designResolutionSize = cocos2d::Size(480, 320);
static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320);
static cocos2d::Size mediumResolutionSize = cocos2d::Size(1024, 768);
static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536);

AppDelegate::AppDelegate()
{
}

AppDelegate::~AppDelegate()
{
}

// if you want a different context, modify the value of glContextAttrs
// it will affect all platforms
void AppDelegate::initGLContextAttrs()
{
    // set OpenGL context attributes: red,green,blue,alpha,depth,stencil
    GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};

    GLView::setGLContextAttrs(glContextAttrs);
}

// if you want to use the package manager to install more packages,
// don‘t modify or remove this function
static int register_all_packages()
{
    return 0; //flag for packages manager
}

// 游戏启动时调用的函数
bool AppDelegate::applicationDidFinishLaunching() {
    // initialize director
    auto director = Director::getInstance();//初始化导演类
    auto glview = director->getOpenGLView();
    if(!glview) {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
        glview = GLViewImpl::createWithRect("NotesDamo", cocos2d::Rect(0, 0, designResolutionSize.width, designResolutionSize.height));
#else
        glview = GLViewImpl::create("NotesDamo");
#endif
        director->setOpenGLView(glview);//设置导演类的OpenGL视图
    }

    // turn on display FPS
    director->setDisplayStats(true);//设置是否在屏幕上显示帧率信息(一般都是为了测试,实际发布时是不会显示的)

    // set FPS. the default value is 1.0/60 if you don‘t call this
    director->setAnimationInterval(1.0f / 60);//一秒执行60帧

    // Set the design resolution
    glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::NO_BORDER);
    auto frameSize = glview->getFrameSize();
    // if the frame‘s height is larger than the height of medium size.
    if (frameSize.height > mediumResolutionSize.height)
    {
        director->setContentScaleFactor(MIN(largeResolutionSize.height/designResolutionSize.height, largeResolutionSize.width/designResolutionSize.width));
    }
    // if the frame‘s height is larger than the height of small size.
    else if (frameSize.height > smallResolutionSize.height)
    {
        director->setContentScaleFactor(MIN(mediumResolutionSize.height/designResolutionSize.height, mediumResolutionSize.width/designResolutionSize.width));
    }
    // if the frame‘s height is smaller than the height of medium size.
    else
    {
        director->setContentScaleFactor(MIN(smallResolutionSize.height/designResolutionSize.height, smallResolutionSize.width/designResolutionSize.width));
    }

    register_all_packages();

    // create a scene. it‘s an autorelease object
    auto scene = HelloWorld::createScene();//创建导演类对象scene

    // run
    director->runWithScene(scene);//运行该场景(会使游戏进入该场景)

    return true;
}

// This function will be called when the app is inactive. Note, when receiving a phone call it is invoked.

//游戏进入后台时调用的函数
void AppDelegate::applicationDidEnterBackground() {
    Director::getInstance()->stopAnimation();//停止场景中的动画

    // if you use SimpleAudioEngine, it must be paused
    // 停止背景音乐,默认时注释掉的
    // SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}

// this function will be called when the app is active again
// 游戏进入前台时调用的函数
void AppDelegate::applicationWillEnterForeground() {
    Director::getInstance()->startAnimation();//开始场景中的动画

    // if you use SimpleAudioEngine, it must resume here
    // 继续背景音乐的,默认是注释掉的
    // SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}

3、HelloWorldScene.h

 1 #ifndef __HELLOWORLD_SCENE_H__
 2 #define __HELLOWORLD_SCENE_H__
 3
 4 #include "cocos2d.h"
 5
 6
 7 /*
 8  *在这里我们可以看出,HelloWorld类继承了cocos2d::Layer类;它被称为层(layer),这些层被放到了场景(scene)中,场景类是:cocos2d::Scene;
 9     注意:HelloWorld.h虽然命名为场景,但是它内部定义的HelloWorld类是一个层
10  */
11 //HelloWorld继承了cocos2d::Layer,HelloWorld是一个层,而不是场景。
12 class HelloWorld : public cocos2d::Layer
13 {
14
15 public:
16
17     static cocos2d::Menu* m_pSelectedItem();
18
19     virtual ~HelloWorld(){}
20
21     static cocos2d::Scene* createScene();//声明创建当前的层HelloWorld所在场景的静态函数createScene();
22
23     virtual bool init();//声明初始化层HelloWorld实例函数。
24
25     // a selector callback
26     void menuCloseCallback(cocos2d::Ref* pSender);//声明菜单回调函数menuCloseCallback,用于触摸菜单事件的回调。
27
28     CREATE_FUNC(HelloWorld);//CREATE_FUNC是cocos2d-x中定义的一个宏(作用是:创建一个静态函数"static create()",该函数可以用来创建层);
29
30
31
32     // implement the "static create()" method manually
33
34 };
35
36 #endif // __HELLOWORLD_SCENE_H__

4、HelloWorldScene.cpp

  1 #include "HelloWorldScene.h"
  2 #include "SimpleAudioEngine.h"
  3
  4 USING_NS_CC;
  5 /*
  6  说明:createScene()函数式是在游戏应用启动的时候,在AppDelegate中的bool AppDelegate::applicationDidFinishLaunching()函数中通过 auto scene = HelloWorld::createScene()语句调用的。
  7     createScene()中做了三件事情,首先创建了HelloWorld层所在的场景对象,其次创建了HelloWorld层,最后将HelloWorld层添加到场景scene中;
  8  */
  9 Scene* HelloWorld::createScene()
 10 {
 11     // ‘scene‘ is an autorelease object
 12     auto scene = Scene::create();
 13
 14     // ‘layer‘ is an autorelease object
 15     // 当调用到这句创建层的时候,会调用HelloWorld的实例函数init(),达到初始化HelloWorld层的目的。
 16     auto layer = HelloWorld::create();
 17
 18     // add layer as a child to scene
 19     scene->addChild(layer);
 20
 21     // return the scene
 22     return scene;
 23 }
 24
 25 // on "init" you need to initialize your instance
 26 bool HelloWorld::init()
 27 {
 28     //////////////////////////////
 29     // 1. super init first
 30     // 初始化父类
 31     if ( !Layer::init() )
 32     {
 33         return false;
 34     }
 35
 36     auto visibleSize = Director::getInstance()->getVisibleSize();
 37     Vec2 origin = Director::getInstance()->getVisibleOrigin();
 38
 39     /////////////////////////////
 40     // 2. add a menu item with "X" image, which is clicked to quit the program
 41     //    you may modify it.
 42
 43     // add a "close" icon to exit the progress. it‘s an autorelease object
 44     // 增加一个菜单项,单机的时候退出程序
 45     auto closeItem = MenuItemImage::create(
 46                                            "CloseNormal.png",
 47                                            "CloseSelected.png",
 48                                            CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
 49
 50     closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
 51                                 origin.y + closeItem->getContentSize().height/2));
 52
 53     // create menu, it‘s an autorelease object
 54     auto menu = Menu::create(closeItem, NULL);
 55     menu->setPosition(Vec2::ZERO);//自定义菜单对象的位置
 56     this->addChild(menu, 1);//把菜单对象添加到当前HelloWorld层上
 57
 58     /////////////////////////////
 59     // 3. add your codes below...
 60
 61     // add a label shows "Hello World"
 62     // create and initialize a label
 63
 64     //添加label标签标题
 65     auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);
 66
 67     // position the label on the center of the screen
 68     label->setPosition(Vec2(origin.x + visibleSize.width/2,
 69                             origin.y + visibleSize.height - label->getContentSize().height));
 70
 71     // add the label as a child to this layer
 72     this->addChild(label, 1);
 73
 74     // add "HelloWorld" splash screen"
 75     //添加精灵,也就是cocos2d-x的logo,定义到屏幕中央
 76     auto sprite = Sprite::create("HelloWorld.png");
 77
 78     // position the sprite on the center of the screen
 79     sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
 80
 81     // add the sprite as a child to this layer
 82     this->addChild(sprite, 0);
 83
 84
 85     return true;
 86 }
 87
 88 // 菜单回调函数(返回主界面)
 89 void HelloWorld::menuCloseCallback(Ref* pSender)
 90 {
 91     //Close the cocos2d-x game scene and quit the application
 92     Director::getInstance()->end();
 93
 94     #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)//IOS表示iOS平台
 95     exit(0);
 96 #endif
 97
 98     /*To navigate back to native iOS screen(if present) without quitting the application  ,do not use Director::getInstance()->end() and exit(0) as given above,instead trigger a custom event created in RootViewController.mm as below*/
 99
100     //EventCustom customEndEvent("game_scene_close_event");
101     //_eventDispatcher->dispatchEvent(&customEndEvent);
102
103
104
105
106 //    PhysicsShape物理引擎类精灵(也属于精灵)
107
108
109 //    节点
110     //(1)创建节点
111     Node * chilNode = Node::create();
112     //(2)查找子节点
113     Node *node = node ->getChildByTag(123);
114     //(3)增加新的子节点
115     node->addChild(chilNode,0,123);
116     //(4)删除子节点,并停止该节点上的一切动作
117     node->removeChildByTag(123,true);
118     //(5)通过NOde指针删除节点
119     node ->removeChild(node);
120     //(6)删除所有子节点,并停止这些节点上的一切动作
121     node ->removeAllChildrenWithCleanup(true);
122     //(7)从父节点中删除 node 节点,并停止该节点上的一切动作。
123     node->removeFromParentAndCleanup(true);
124     /*Node重要属性*/
125 //    setPosition; 坐标
126 //    setAnchorPoint(Vce2(0.5,.05)); 锚点
127
128
129
130
131     //坐标
132 //    Vec2 touchLocation = touch ->getLocationInView();
133 //    Vec2 touchLocation2 = Director::getInstance()->convertToGL(touchLocation);
134
135
136 }
137
138
139 /**
140  cocos2d-x的事件响应机制:即菜单层最先接收到系统事件,则排在后面的是精灵层,最后是背景层,在事件的传递过程中 ,如果有一个层处理了该事件,则排在后面的层将不再接受到该事件。
141  */
时间: 2024-12-26 01:20:48

cocos2d-x C++ 原始工程引擎运行机制解析的相关文章

[转]OpenStack Neutron运行机制解析概要

转载自:http://panpei.net.cn/2013/12/04/openstack-neutron-mechanism-introduce/ 自从开学以来,玩OpenStack也已经3个月了,这段时间主要把精力投在了OpenStack的安装部署和网络组件Neutron的研究上了.这期间零零散散在安装部署和Neutron运作原理上来回切换,有点在实践中学习的味道,虽然在安装部署的过程遇到了不少的问题,也一一都给解决了.然而,总是觉得对于Neutron的机制理解的还是不够透彻.前一阵子刚刚部

【JS】JavaScript引擎的内部运行机制

首先看一段小程序: <script> alert('第1'); setTimeout(function(){<pre name="code" class="javascript"><span style="white-space:pre"> </span>alert('第2'); }, 2000); alert('第3');</script> 输出顺序是:第1,第3,第2:再来看一段小程

MVC运行机制[转]

原:http://www.cnblogs.com/jyan/archive/2012/06/29/2569566.html#3122335 ASP.NET是一种建立动态Web应用程序的技术.它是.NET框架的一部分,可以使用任何.NET兼容的语言编写ASP.NET应用程序.相对于Java.PHP等,ASP.NET具有方便性.灵活性.性能优.生产效率高.安全性高.完整性强及面向对象等特性,是目前主流的网络编程技术之一.它可以让开发者快速高效的创建应用程序而不必关注Http,Html,Javascr

Javascript引擎单线程机制及setTimeout执行原理说明

setTimeout用法在实际项目中还是会时常遇到.比如浏览器会聪明的等到一个函数堆栈结束后才改变DOM,如果再这个函数堆栈中把页面背景先从白色设为红色,再设回白色,那么浏览器会认为DOM没有发生任何改变而忽略这两句话,因此我们可以通过setTimeout把“设回白色”函数加入下一个堆栈,那么就可以确保背景颜色发生过改变了(虽然速度很快可能无法被察觉). 总之,setTimeout增加了Javascript函数调用的灵活性,为函数执行顺序的调度提供极大便利. 然后,我们从基础的层面来看看:理解J

JavaScript运行机制浅析

从一个简单的问题谈起: <script type="text/javascript"> alert(i); var i = 1; </script> 输出结果是undefined, 这种现象被称成“预解析”:JavaScript引擎会优先解析var变量和function定义.在预解析完成后,才会执行代码.如果一个文档流中包含多个script代码段(用script标签分隔的js代码或引入的js文件). 运行顺序是: step1. 读入第一个代码段step2. 做语

.NET那点事 (02).NET运行机制

.NET运行机制1 .NET程序被编译成什么形式的代码2 JIT是如何工作的3 简述程序集的加载机制4 如何配置程序集的版本策略 1 .NET程序被编译成什么形式的代码 .NET程序在编写完成后,会经过第一次编译.对于C#而言,无论是VS IDE还是其他任何间接方式,本质上都是执行编译器cse.exe来编译C#代码.在这次编译之后,程序会被编译成中间代码(IL),并且所有必须的元数据和程序集会被一起打包加载到文件头上.编译后的文件是一个标准的PE/COFF应用文件,该文件的最开始的部分包含了PE

(转)浅析JS运行机制

原文 从一个简单的问题谈起: 1 <script type="text/javascript"> 2 alert(i); // ? 3 var i = 1; 4 </script> 输出结果是undefined, 这种现象被称成“预解析”:JavaScript引擎会优先解析var变量和function定义.在预解析完成后,才会执行代码.如果一个文档流中包含多个script代码段(用script标签分隔的js代码或引入的js文件),运行顺序是: 1 step1.

【朴灵评注】JavaScript 运行机制详解:再谈Event Loop

PS: 我先旁观下大师们的讨论,得多看书了~ 别人说的:“看了一下不觉得评注对到哪里去,只有吹毛求疵之感. 比如同步异步介绍,本来就无大错:比如node图里面的OS operation,推敲一下就可以猜到那是指同步操作(自然不走event loop了):至于watcher啥的,显然只是实现上的特色,即使用同一个queue实现也未尝不可” [原帖: http://www.ruanyifeng.com/blog/2014/10/event-loop.html 作者:阮一峰] 一年前,我写了一篇<什么

【repost】JavaScript 运行机制详解:再谈Event Loop

一年前,我写了一篇<什么是 Event Loop?>,谈了我对Event Loop的理解. 上个月,我偶然看到了Philip Roberts的演讲<Help, I'm stuck in an event-loop>.这才尴尬地发现,自己的理解是错的.我决定重写这个题目,详细.完整.正确地描述JavaScript引擎的内部运行机制.下面就是我的重写. 进入正文之前,插播一条消息.我的新书<ECMAScript 6入门>出版了(版权页,内页1,内页2),铜版纸全彩印刷,非常