新建一個工程,相信感興趣的同學都想知道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 */
?