天天看点

学习cocos2d-x之路(3)--创建第一个场景

创建我的第一个场景

学习cocos2d-x之路(3)--创建第一个场景

运行 install-templates-msvc.bat,VS2010将会安装cocos2D-X的模板,新建项目时可以直接建立一个HelloWorld应用。

删除HelloWolrldScene.cpp中不需要的部分,使用Tiled地图编辑器绘制地图后保存到工程目录Resource下,在HelloWorld::init()中创建地图:

CCTMXTiledMap *map=CCTMXTiledMap::create("1.tmx");     //旧的cocos2d-x使用 :: tiledMapWithTmxFile(char *),新的版本此方法已经删除

   CC_BREAK_IF(! map);

  this->addChild(map);

增加函数createHeroSprite()创建一个4帧的循环播放的Hero精灵,需要在HelloWorld::init()中调用此函数

void HelloWorld::createHeroSprite()

{

 CCTexture2D *heroTex=CCTextureCache::sharedTextureCache()->addImage("hero.png");    //将纹理加入全局纹理缓冲区,并创建返回纹理

 CCSpriteFrame * frame0,*frame1,*frame2,*frame3;                                                                   //创建4帧动画

 frame0=CCSpriteFrame::createWithTexture(heroTex,CCRectMake(32*0,0,32,32));

 frame1=CCSpriteFrame::createWithTexture(heroTex,CCRectMake(32*1,0,32,32));

 frame2=CCSpriteFrame::createWithTexture(heroTex,CCRectMake(32*2,0,32,32));

 frame3=CCSpriteFrame::createWithTexture(heroTex,CCRectMake(32*3,0,32,32));

 CCArray * animFrames= CCArray::create();                                                                      //用CCArray保存动画帧,旧的版本使用CCMutableArray<T>,新版本已经删除

 animFrames->addObject(frame0);

 animFrames->addObject(frame1);

 animFrames->addObject(frame2);

 animFrames->addObject(frame3);

 CCAnimation * animation=CCAnimation::createWithSpriteFrames(animFrames,0.2); 

 animFrames->release();

 CCSprite * heroSprite=CCSprite::createWithSpriteFrame(frame0);//使用第一帧创建精灵

 heroSprite->setPosition(ccp(32,32*8));

 this->addChild(heroSprite);

 CCAnimate * animatie=CCAnimate::create(animation);                            创建动画

 heroSprite->runAction(CCRepeatForever::create(animatie));

}