首页 > 代码库 > 1 游戏逻辑架构,Cocos2d-x游戏项目创建,HelloWorld项目创建,HelloWorld程序分析,(CCApplicationProtocol,CCApplication,AppDeleg
1 游戏逻辑架构,Cocos2d-x游戏项目创建,HelloWorld项目创建,HelloWorld程序分析,(CCApplicationProtocol,CCApplication,AppDeleg
1游戏逻辑架构
具体介绍
A一个导演同一时间仅仅能执行一个场景,场景其中,能够同一时候载入多个层,一个层能够可载多个精灵。层中亦能够加层。 |
B 场景切换 sceneàaddChild(layer); layeràaddChild(sprite); |
2项目创建命令:
A进入tools下的project-creat E:\Installed\cocos2d-x-2.2.3\tools\project-creator> |
B python create_project.py -project MyCocos2dx -package com.toto.mycocos01 -language cpp |
C命令解释: -project MyCocos2dx工程名 -package com.toto.mycocos01包名 -language cpp开发语言可选项目有javascript lua |
D创建后的项目文件夹: |
3 简单介绍
1查看cocos2dx游戏的版本号信息。 创建了一个cocos2dx项目之后,打开项目之后,会有例如以下项目结构 展开libcocos2d,找到cocos2d.cpp,双击打开此cpp文件,内容例如以下:
#include"cocos2d.h"
NS_CC_BEGIN
constchar*cocos2dVersion() { return"2.2.3"; }
NS_CC_END
截图例如以下: 分析: A 由上能够看出项目的版本是:2.2.3 B 依赖的头文件“cocos2d.h” |
|
2查看程序入口 |
程序入口是:main.cpp |
#include"main.h" #include"AppDelegate.h" #include"CCEGLView.h"
USING_NS_CC;
intAPIENTRY_tWinMain(HINSTANCEhInstance, HINSTANCEhPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine);
// create the application instance AppDelegateapp; //Delegate:表示委派…为代表 n:代表 CCEGLView*eglView =CCEGLView::sharedOpenGLView(); eglView->setViewName("MyCocos2dx"); //程序的标题 eglView->setFrameSize(480, 320); //程序的尺寸 returnCCApplication::sharedApplication()->run(); //关于shared的通常是单例模式 } |
进入run函数, run的代码结构例如以下(选中run(),再按F12进行查看): |
intCCApplication::run() { PVRFrameEnableControlWindow(false);
// Main message loop: MSGmsg; LARGE_INTEGERnFreq; LARGE_INTEGERnLast; LARGE_INTEGERnNow;
QueryPerformanceFrequency(&nFreq); QueryPerformanceCounter(&nLast);
// Initialize instance and cocos2d. if (!applicationDidFinishLaunching()) { return 0; }
CCEGLView*pMainWnd =CCEGLView::sharedOpenGLView(); pMainWnd->centerWindow(); ShowWindow(pMainWnd->getHWnd(),SW_SHOW);
while (1) { if (!PeekMessage(&msg,NULL, 0, 0,PM_REMOVE)) { // Get current time tick. QueryPerformanceCounter(&nNow);
// If it‘s the time to draw next frame, draw it, else sleep a while. if (nNow.QuadPart - nLast.QuadPart > m_nAnimationInterval.QuadPart) { nLast.QuadPart = nNow.QuadPart; CCDirector::sharedDirector()->mainLoop(); } else { Sleep(0); } continue; }
if (WM_QUIT == msg.message) { // Quit message loop. break; }
// Deal with windows message. if (!m_hAccelTable || !TranslateAccelerator(msg.hwnd,m_hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } }
return (int)msg.wParam; } |
程序的入口:applicationDidFinishLaunching() |
|
AppDelegate.cpp boolAppDelegate::applicationDidFinishLaunching() { // initialize director CCDirector*pDirector =CCDirector::sharedDirector(); CCEGLView*pEGLView =CCEGLView::sharedOpenGLView();
pDirector->setOpenGLView(pEGLView);
// turn on display FPS pDirector->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don‘t call this pDirector->setAnimationInterval(1.0 / 60); //设置帧率
// create a scene. it‘s an autorelease object CCScene *pScene = HelloWorld::scene();
// run pDirector->runWithScene(pScene);
returntrue; } 截图: |
|
HelloWorldScene.h HelloWorld类的本质是一个层(CCLayer): |
#ifndef__HELLOWORLD_SCENE_H__ #define__HELLOWORLD_SCENE_H__
#include"cocos2d.h"
classHelloWorld :publiccocos2d::CCLayer { public: // Here‘s a difference. Method ‘init‘ in cocos2d-x returns bool, instead of returning ‘id‘ in cocos2d-iphone virtualboolinit();
// there‘s no ‘id‘ in cpp, so we recommend returning the class instance pointer staticcocos2d::CCScene*scene();
// a selector callback voidmenuCloseCallback(CCObject*pSender);
// implement the "static node()" method manually CREATE_FUNC(HelloWorld); };
#endif// __HELLOWORLD_SCENE_H__
|
HelloWorldScene.cpp |
#include"HelloWorldScene.h"
USING_NS_CC;
CCScene*HelloWorld::scene() { // ‘scene‘ is an autorelease object CCScene *scene = CCScene::create();
// ‘layer‘ is an autorelease object HelloWorld *layer = HelloWorld::create();
// add layer as a child to scene scene->addChild(layer);
//return the scene returnscene; }
// on "init" you need to initialize your instance boolHelloWorld::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { returnfalse; }
CCSizevisibleSize =CCDirector::sharedDirector()->getVisibleSize(); CCPointorigin =CCDirector::sharedDirector()->getVisibleOrigin();
///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it.
// add a "close" icon to exit the progress. it‘s an autorelease object CCMenuItemImage *pCloseItem = CCMenuItemImage::create( "CloseNormal.png", "CloseSelected.png", this, menu_selector(HelloWorld::menuCloseCallback));
pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 , origin.y + pCloseItem->getContentSize().height/2));
// create menu, it‘s an autorelease object CCMenu*pMenu =CCMenu::create(pCloseItem,NULL); pMenu->setPosition(CCPointZero); this->addChild(pMenu, 1);
///////////////////////////// // 3. add your codes below...
// add a label shows "Hello World" // create and initialize a label
CCLabelTTF*pLabel =CCLabelTTF::create("Hello World","Arial", 24);
// position the label on the center of the screen pLabel->setPosition(ccp(origin.x + visibleSize.width/2, origin.y + visibleSize.height - pLabel->getContentSize().height));
// add the label as a child to this layer this->addChild(pLabel, 1);
// add "HelloWorld" splash screen" CCSprite*pSprite =CCSprite::create("HelloWorld.png");
// position the sprite on the center of the screen pSprite->setPosition(ccp(visibleSize.width/2 + origin.x,visibleSize.height/2 + origin.y));
// add the sprite as a child to this layer this->addChild(pSprite, 0);
returntrue; }
voidHelloWorld::menuCloseCallback(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 }
|
总结: 1、对于cocos真正的初始化是在init()方法中 2、CCScene中的 autorelease()完毕了析构的过程 3、CCPointZero表示的位置是CCPointMake(0,0); |
4(CCApplicationProtocol,CCApplication,AppDelegate)三个类的类关系介绍:
抽出代码详细实现:
长处:屏蔽了平台的差异性,实现跨平台
1 CCApplicationProtocol 定义了接口 #ifndef__CC_APPLICATION_PROTOCOL_H__ #define__CC_APPLICATION_PROTOCOL_H__
NS_CC_BEGIN
enumTargetPlatform { kTargetWindows, kTargetLinux, kTargetMacOS, kTargetAndroid, kTargetIphone, kTargetIpad, kTargetBlackBerry, kTargetNaCl, kTargetEmscripten, kTargetTizen, kTargetWinRT, kTargetWP8 };
/** * @addtogroup platform * @{ * @js NA * @lua NA */
classCC_DLLCCApplicationProtocol { public:
virtual ~CCApplicationProtocol() {}
/** @brief Implement CCDirector and CCScene init code here. @return true Initialize success, app continue. @return false Initialize failed, app terminate. */ virtualboolapplicationDidFinishLaunching() = 0; //这个类是一个纯虚函数
/** @brief The function be called when the application enter background @param the pointer of the application */ virtualvoidapplicationDidEnterBackground() = 0;
/** @brief The function be called when the application enter foreground @param the pointer of the application */ virtualvoidapplicationWillEnterForeground() = 0;
/** @brief Callback by CCDirector for limit FPS. @interval The time, expressed in seconds, between current frame and next. */ virtualvoidsetAnimationInterval(doubleinterval) = 0;
/** @brief Get current language config @return Current language config */ virtualccLanguageTypegetCurrentLanguage() = 0;
/** @brief Get target platform */ virtualTargetPlatformgetTargetPlatform() = 0; };
// end of platform group /// @}
NS_CC_END
#endif // __CC_APPLICATION_PROTOCOL_H__
|
2 CCApplication 各个平台不同的逻辑 |
3 AppDelegate 私有继承了CCApplication仅实现CCApplicationProtocol里的接口 |
1 游戏逻辑架构,Cocos2d-x游戏项目创建,HelloWorld项目创建,HelloWorld程序分析,(CCApplicationProtocol,CCApplication,AppDeleg