最近刚刚开始学习cocos2d-x,本身自己就是小菜外加从未涉足过游戏引擎方面,而相关的C++版本学习教程并不多,自学起来很是费力啊!

首先是引擎相关的最基本概念,参见http://leeyin.iteye.com/blog/1166940。。

生成的项目Classes文件夹下即为主要实现代码,HelloWorldAppDelegate类用于处理应用程序中的全局事件和状态变化,HelloWorldScene为具体界面及程序中操作的实现。

所有发生在main函数和HelloWorldAppDelegate类之间的事情都是由VS自行处理的,不受程序员控制.

 

HelloWorld类继承自CCLayer类,主要有4个public方法:

 
  
  1. // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone 
  2. virtual bool init();   
  3.  
  4. // there's no 'id' in cpp, so we recommand to return the exactly class pointer 
  5. static cocos2d::CCScene* scene(); 
  6.  
  7. // a selector callback 
  8. virtual void menuCloseCallback(CCObject* pSender); 
  9.  
  10. // implement the "static node()" method manually 
  11. LAYER_NODE_FUNC(HelloWorld); 

init()方法用于helloworld界面初始化,具体完成了背景图加载,label文字加载,关闭按钮加载.

 
  
  1. //C++中不能用super::init(),而必须老老实实地指定是执行父类CCLayer::init()方法  
  2. CC_BREAK_IF(! CCLayer::init());   

 
  
  1. CCMenuItemImage *pCloseItem = CCMenuItemImage::itemFromNormalImage( 
  2.             "CloseNormal.png"
  3.             "CloseSelected.png"
  4.             this
  5.             menu_selector(HelloWorld::menuCloseCallback)) 

上述代码实现了关闭按钮项对关闭按钮图片加载及回调函数的载入,需要说明的是1.CPP中this代替了objc的self关键字。2.每种回调函数都有唯一类型的函数指针与之匹配,这里就是menu_selector回调函数类型。

 
  
  1. // Create a menu with the "close" menu item, it's an auto release object. 
  2.         CCMenu* pMenu = CCMenu::menuWithItems(pCloseItem, NULL); 
  3.         pMenu->setPosition(CCPointZero); 
  4.         CC_BREAK_IF(! pMenu); 
  5.  
  6.         // Add the menu to HelloWorld layer as a child layer. 
  7.         this->addChild(pMenu, 1);  

上述代码创建了CCMenu实例,需要说明的是menuWithItems的最后一个参数必须为NULL。创建完成后要将实例用addChild加载到层里,实现整体化,而addChild第二个参数就是层数的标号,一个场景往往是多个层的叠加,所以序号成为决定了显示的效果的因素之一。

之后的创建label及载入图片过程与此相似,不再赘述。

 

virtual void menuCloseCallback(CCObject* pSender)方法只有一句话

CCDirector::sharedDirector()->end();

在用户点击按钮时调用了静态的总导演的end方法来实现退出程序。

 

LAYER_NODE_FUNC(HelloWorld)方法即为HelloWorld的node方法,HelloWorld类继承与CCNode类,继承的node方法在调用基类方法后便会调用init()方法来实现初始化。

 

最后是static cocos2d::CCScene* scene(),这个方法是为了实现场景类的实例,场景类作为层(CCLayer)的容器。在这个项目的结构组织上是将构建场景(class HelloWorldScene)的方法归属于派生的层类(class HelloWorld)之中,

方法中首先构造场景,然后构造层及初始化函数init(),完成初始化后将层加入到场景中并返回场景实例。

程序的整个流程大概是从applicationDidFinishLaunching中的CCScene *pScene = HelloWorld::scene()开始,然后static cocos2d::CCScene* scene(); 在其中会调用LAYER_NODE_FUNC(HelloWorld),node方法

会调用virtual bool init();,而virtual void menuCloseCallback(CCObject* pSender);被init

调用,最后初始化完成,回到appdelegate,由导演调用ranWithScene进行显示第一个场景。

 

appdelegate.cpp中应用程序收到的第一个消息会是applicationDidFinishLaunching方法,这是所有代码的起始位置,在APPDelegate类中.

 
  
  1. CCScene *pScene = HelloWorld::scene(); 
  2. // run 
  3. pDirector->runWithScene(pScene); 

实例化初始场景并由总导演进行调用。