这篇算是cocos2d-x入门篇,显示一张图片即可。
观察工程中HelloWorld的结构,包含AppDelegate和HelloWorldScene两个类文件,AppDelegate中包含基本的处理,并且创建最初要显示的Scene并运行之。
而HelloWorldScene中则做了相关的初始化工作,在这里,自己仿照HelloWorldScene写个更简单的Scene用于显示。
AppDelegate.cpp内容
1 #include "AppDelegate.h" 2 //#include "HelloWorldScene.h" 3 #include "MyScene.h" 4 5 USING_NS_CC; 6 7 AppDelegate::AppDelegate() { 8 9 } 10 11 AppDelegate::~AppDelegate() 12 { 13 } 14 15 bool AppDelegate::applicationDidFinishLaunching() { 16 // initialize director 17 CCDirector* pDirector = CCDirector::sharedDirector(); 18 CCEGLView* pEGLView = CCEGLView::sharedOpenGLView(); 19 20 pDirector->setOpenGLView(pEGLView); 21 22 // turn on display FPS 23 pDirector->setDisplayStats(true); 24 25 // set FPS. the default value is 1.0/60 if you don't call this 26 pDirector->setAnimationInterval(1.0 / 60); 27 28 // create a scene. it's an autorelease object 29 //CCScene *pScene = HelloWorld::scene(); 30 CCScene *pScene = MyScene::createScene(); 31 32 // run 33 pDirector->runWithScene(pScene); 34 35 return true; 36 } 37 38 // This function will be called when the app is inactive. When comes a phone call,it's be invoked too 39 void AppDelegate::applicationDidEnterBackground() { 40 CCDirector::sharedDirector()->stopAnimation(); 41 42 // if you use SimpleAudioEngine, it must be pause 43 // SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic(); 44 } 45 46 // this function will be called when the app is active again 47 void AppDelegate::applicationWillEnterForeground() { 48 CCDirector::sharedDirector()->startAnimation(); 49 50 // if you use SimpleAudioEngine, it must resume here 51 // SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); 52 }
MyScene.h内容
1 #ifndef MyScene_H_H 2 #define MyScene_H_H 3 4 #include "cocos2d.h" 5 using namespace cocos2d; 6 7 class MyScene : public CCLayer 8 { 9 public: 10 static CCScene* createScene(); 11 virtual bool init(); 12 CREATE_FUNC( MyScene ); 13 14 15 private: 16 }; 17 18 #endif
MyScene.cpp内容
1 #include "MyScene.h" 2 3 CCScene* MyScene::createScene() 4 { 5 CCScene *scene = CCScene::create(); 6 MyScene *layer = MyScene::create(); 7 scene->addChild(layer); 8 return scene; 9 }; 10 11 12 bool MyScene::init() 13 { 14 if( !CCLayer::init() ){ 15 return false; 16 } 17 CCSize size = CCDirector::sharedDirector()->getWinSize(); 18 CCSprite *sprite = CCSprite::create("pal4.png"); 19 sprite->setAnchorPoint( ccp(0.5f, 0.5f) ); 20 sprite->setPosition( ccp(size.width/2, size.height/2) ); 21 sprite->setScale(0.5f); 22 addChild(sprite); 23 24 return true; 25 }
运行结果: