您的位置:首页 > 移动开发 > Cocos引擎

cocos2d-x基础<二>

2012-02-13 14:16 363 查看
1.程序入口

程序入口为cocos2d::CCApplication::run()。这里的CCApplication是单件,所以只需要从它派生一个子类,如HelloWorld中的AppDelegate,原来调用以下代码:

AppDelegate app;
return cocos2d::CCApplication::sharedApplication().run();


2.创建程序窗口

在AppDelegate::initInstance()中,可以根据CC_TARGET_PLATFORM的值判断程序的运行平台,在CC_PLATFORM_WIN32下创建程序窗口的代码如下:

CCEGLView * pMainWnd = new CCEGLView();
CC_BREAK_IF(! pMainWnd|| ! pMainWnd->Create(TEXT("cocos2d: Hello World"), 480, 320));


3.开始场景循环

在AppDelegate::applicationDidFinishLaunching()中,可以实例化CCDirector和CCScene。注意下面的HelloWorld类其实是继承了CCLayer的,但是在HelloWorld::scene()方法中创建了一个简单的CCScene实例并返回了。

// initialize director
CCDirector *pDirector = CCDirector::sharedDirector();
pDirector->setOpenGLView(&CCEGLView::sharedOpenGLView());

// enable High Resource Mode(2x, such as iphone4) and maintains low resource on other devices.
// pDirector->enableRetinaDisplay(true);

// turn on display FPS
pDirector->setDisplayFPS(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);

在tests项目的AppDelegate::applicationDidFinishLaunching()中,创建场景的方式看起来不同,但其实和上面是一样的。TestController是继承了CCLayer的,只是这里把创建新CCScene实例的代码提出来,而没有封装到TestController中。代码如下:
CCScene * pScene = CCScene::node();
CCLayer * pLayer = new TestController();
pLayer->autorelease();

pScene->addChild(pLayer);
pDirector->runWithScene(pScene);


4.响应用户输入

用户输入的响应接口在cocos2d::CCLayer中,包括ccTouchesBegan、ccTouchesMoved、ccTouchesEnded、ccTouchesCancelled等,所以如果一个CCScene实例需要处理用户输入,那么这个CCScene至少要包含CCLayer,并在该CCLayer中处理事件。

上面的HelloWorld的例子,HelloWorld这个类就是继承了CCLayer的,所以它能接收用户输入。

5.场景切换

在tests项目的TestController::menuCallback(CCObject*pSender)中,响应用户点击菜单的事件,并切换到需要的演示场景。切换场景的代码为:

TestScene* pScene = CreateTestScene(nIdx);
if (pScene)
{
pScene->runThisTest();
pScene->release();
}

假如要进行ActionManagerTest,则CreateTestScene(nIdx)会创建一个ActionManagerTestScene的实例并返回,而ActionManagerTestScene::runThisTest()的代码如下:
void ActionManagerTestScene::runThisTest()
{
CCLayer* pLayer = nextActionManagerAction();
addChild(pLayer);

CCDirector::sharedDirector()->replaceScene(this);
}

创建一个CCLayer实例给this,然后直接调用CCDirector::replaceScene(this)切换场景,恩,很直接……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: