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,stencilGLContextAttrs 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 directorauto 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));
#elseglview = GLViewImpl::create("NotesDamo");
#endifdirector->setOpenGLView(glview);//設置導演類的OpenGL視圖
    }// turn on display FPSdirector->setDisplayStats(true);//設置是否在屏幕上顯示幀率信息(一般都是為了測試,實際發布時是不會顯示的)// set FPS. the default value is 1.0/60 if you don't call thisdirector->setAnimationInterval(1.0f / 60);//一秒執行60幀// Set the design resolutionglview->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 objectauto scene = HelloWorld::createScene();//創建導演類對象scene// rundirector->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  */

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/395421.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395421.shtml
英文地址,請注明出處:http://en.pswp.cn/news/395421.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

web高德maker動畫_Web Maker —我如何構建一個快速的離線前端游樂場

web高德maker動畫by kushagra gour由kushagra gour Web Maker —我如何構建一個快速的離線前端游樂場 (Web Maker — How I built a fast, offline front-end playground) Web Maker is a Chrome extension that gives you a blazing fast and offline front-end playground —…

時間小知識對于時間轉換可能有幫助

那么UTC與世界各地的時間應如何換算呢?它是將全世界分為24個時區,地球的東、西經各180(共360)被24個時區平分,每個時區各占15。以經度0(即本初子午線)為基準,東經730′與西經730′之間的區域為零時區;東經和西經的730′與2230′之…

JS——實現短信驗證碼的倒計時功能(沒有驗證碼,只有倒計時)

1、功能描述 當用戶想要獲取驗證碼時,就點擊 免費獲取驗證碼 ,然后開始倒計時,倒計時期間按鈕文字為剩余時間x秒,且不可按狀態,倒計時結束后,按鈕更改為點擊重新發送。 2、分析 必須用到定時器。按鈕點擊后…

華為OV小米鴻蒙,華為鴻蒙開源,小米OV們會采用嗎?

華為曾一直聲言不會進入電視市場,由此其他國產電視企業才會采用華為的可見企業是非常擔憂同業競爭關系的,而在智能手機市場,華為毫無疑問與其他國產手機企業都是競爭對手,更何況就在2019年下半年和2020年上半年華為在國內手機市場的份額超過四成直逼五成,其他國產手機企業被壓得…

第22天:如何使用OpenAI Gym和Universe構建AI游戲機器人

by Harini Janakiraman通過哈里尼賈納基拉曼 第22天:如何使用OpenAI Gym和Universe構建AI游戲機器人 (Day 22: How to build an AI Game Bot using OpenAI Gym and Universe) Let’s face it, AI is everywhere. A face-off battle is unfolding between Elon Musk…

軟件測試基礎理論(總結)

1. 軟件的三個要素:程序(實行特定功能的代碼) 文檔(支持代碼運行) 數據(支持程序運行一切有關) 2. 軟件的產品質量 指的是? 1)質量是指實體特性…

android studio 7200u,#本站首曬# 多圖殺貓 華為MateBook X上手體驗

#本站首曬# 多圖殺貓 華為MateBook X上手體驗2017-06-09 18:45:4437點贊33收藏78評論前幾天華為開了個發布會,帶來了三款筆記本電腦,有幸在第一時間借到了MateBook X,現在就來來做一個簡單的上手,稍晚一些再跟大家詳細聊聊使用起來…

svn強制解鎖的幾種做法

標簽: svn強制解鎖2013-12-16 17:40 12953人閱讀 評論(0) 收藏 舉報分類:SoftwareProject(23) 版權聲明:本文為博主原創文章,未經博主允許不得轉載。 作者:朱金燦 來源:http://blog.…

數據結構和算法練習網站_視頻和練習介紹了10種常見數據結構

數據結構和算法練習網站“Bad programmers worry about the code. Good programmers worry about data structures and their relationships.” — Linus Torvalds, creator of Linux“糟糕的程序員擔心代碼。 好的程序員擔心數據結構及其關系。” — Linux的創建者Linus Torva…

突然討厭做前端,討厭代碼_有關互聯網用戶最討厭的廣告類型的新數據

突然討厭做前端,討厭代碼You know that feeling when you’re scrolling through a blog post and then — BAM! — one of those “Sign up for our newsletter” modals pops up?當您滾動瀏覽博客文章,然后-BAM時,您就會知道這種感覺。 -彈出“注冊我…

iOS設計模式-生成器

定義&#xff1a;將一個產品的內部表象與產品的生成過程分割開來&#xff0c;從而可以使一個建造過程生成具有不同的內部表象的產品對象。 類型&#xff1a;對象創建 類圖&#xff1a; #import <Foundation/Foundation.h> interface Character : NSObject property(nonat…

《Android 應用案例開發大全(第二版)》——導讀

本節書摘來自異步社區《Android 應用案例開發大全&#xff08;第二版&#xff09;》一書中的目錄 &#xff0c;作者 吳亞峰 , 于復興 , 杜化美&#xff0c;更多章節內容可以訪問云棲社區“異步社區”公眾號查看 目 錄 第1章 初識廬山真面目——Android簡介 1.1 Android的誕生 1…

模塊--sys模塊

sys模塊是與python解釋器交互的一個接口 import sys sys.path #python解釋器找模塊的環境變量import sys print(sys.path)結果:[H:\\王文靜\\python\\4練習\\課堂練習, H:\\王文靜\\python, C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\pyth…

匿名方法

與前面的可空類型是一樣的&#xff0c;匿名方法也是C# 2.0里面提出來的。 1 匿名方法 1.1 什么是匿名方法&#xff1f; 顧名思義&#xff0c;就是沒有名稱的方法&#xff0c;因為沒有名稱&#xff0c;匿名方法只能在函數定義&#xff08;匿名方法是把方法的實現和定義嵌套在了一…

使用React,Redux和Router進行真正的集成測試

by Marcelo Lotif通過馬塞洛洛蒂夫(Marcelo Lotif) 使用React&#xff0c;Redux和Router進行真正的集成測試 (Real integration tests with React, Redux and Router) After being bitten a couple of times by bad refactoring and a broken app?—?even with all my tests…

Go語言從入門到精通 - 數據類型轉換

本節核心內容 介紹 Go語言數據類型轉換的格式介紹 數據轉換代碼示例介紹 數據轉換過程中的注意事項 本小節視頻教程和代碼&#xff1a;百度網盤 可先下載視頻和源碼到本地&#xff0c;邊看視頻邊結合源碼理解后續內容&#xff0c;邊學邊練。 Go語言數據類型轉換 Go 語言使用類型…

JNI通過線程c回調java層的函數

1、參看博客&#xff1a;http://www.jianshu.com/p/e576c7e1c403 Android JNI 篇 - JNI回調的三種方法&#xff08;精華篇&#xff09; 2、參看博客&#xff1a; JNI層線程回調Java函數關鍵點及示例 http://blog.csdn.net/fu_shuwu/article/details/41121741 3 http://blog.cs…

signature=f7a4b29b93ef2b36608792fdef7f454a,Embedding of image authentication signatures

摘要&#xff1a;A method (), an apparatus, a computer readable medium and use of said method for authenticating an audio-visual signal (), such as a digital image or video, are disclosed. A signature is derived from all image regions, including areas with …

glob

主要是用來在匹配文件&#xff0c;相當shell中用通配符匹配. 用法: glob.glob(pathname) # 返回匹配的文件作為一個列表返回 glob.iglob(pathname) # 匹配到的文件名&#xff0c;返回一個迭代器 ps: pathname是路徑, 可以是絕對和相對路徑 匹配當前目錄下有一個數字開頭…

構建微服務:Spring boot 入門篇

Spring官方網站本身使用Spring框架開發&#xff0c;隨著功能以及業務邏輯的日益復雜&#xff0c;應用伴隨著大量的XML配置文件以及復雜的Bean依賴關系。隨著Spring 3.0的發布&#xff0c;Spring IO團隊逐漸開始擺脫XML配置文件&#xff0c;并且在開發過程中大量使用“約定優先配…