前面一篇中我们绘制了一张简单的地图,包括地板层和墙壁层。但略显单调,因为既没有人物,地图也无法拖动。下面我们就来给地图加上可以行走的勇士。
我们将案例Resource里面的hero.png图片复制到我们的工程MTGame的Resource目录下。
然后在上一篇的基础上,修改HelloWorld.cpp的init函数,在解析tmx地图方法下面,即addChild(map);添加如下代码
//将图片生成纹理,保存到全局的纹理缓冲区
CCTexture2D *heroTexture=CCTextureCache::sharedTextureCache()->addImage("hero.png");
//创建四个纹理
CCSpriteFrame *frame0,*frame1,*frame2,*frame3;
//第二个参数表示显示区域的x, y, width, height
frame0=CCSpriteFrame::createWithTexture(heroTexture,CCRectMake(32*0,32*0,32,32));
frame1=CCSpriteFrame::createWithTexture(heroTexture,CCRectMake(32*1,32*0,32,32));
frame2=CCSpriteFrame::createWithTexture(heroTexture,CCRectMake(32*2,32*0,32,32));
frame3=CCSpriteFrame::createWithTexture(heroTexture,CCRectMake(32*3,32*0,32,32));
//在2.0版本以后,CCMutableArray取消了
CCArray* animFrames=new CCArray(4);
//将创建的四个纹理保存到数组中
animFrames->addObject(frame0);
animFrames->addObject(frame1);
animFrames->addObject(frame2);
animFrames->addObject(frame3);
//创建一个动画
CCAnimation* animation=new CCAnimation();
//0.2f表示每帧动画间的间隔
animation->initWithSpriteFrames(animFrames,0.2f);
animFrames->release();
//用frame0作为勇士的静态图
CCSprite* heroSprite=CCSprite::createWithSpriteFrame(frame0);
//暂时将勇士显示在(100,100)处
heroSprite->setPosition(ccp(100,100));
addChild(heroSprite);
//创建动画
CCAnimate* animate=CCAnimate::create(animation);
//让精灵播放定义的动画,就有了行走的效果
heroSprite->runAction(CCRepeatForever::create(animate));
运行,效果如下,画面左下角出现了一个勇士在不停地走动。