在cocos2d-x系列笔记(4)---会动的小精灵一文中,我们介绍了如何用程序裁切图片,创建一个会动的精灵.但这样的做法在实际开发中会比较难用.所以我在这里对上一篇文章进行一个补充,讲述一下实际工作中比较实用的规划纹理资源和创建精灵的方法.
TexturePacker这个软件不少人都在用,它可以把若干图片合并成一副图,并生成一个plist文件,用来描述生成的图片中每一帧图片的信息.cocos2d-x也对plist文件进行了支持.
TexturePacker的用法我就不详细介绍了,用法很简单,无非是拖进每一帧的图片,点下publish发布出合并后的大图与plist文件.
主要讲一下cocos2d-x如何使用这两种资源.上代码:
CCArray *len_AniFrames = new CCArray(4); //加载plist文件,通过plist文件加载纹理资源 CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Len.plist"); for(int i=0;i<4;i++) { //初始化内存 memset(charBuffer,0,sizeof(charBuffer)); //组合字符串,4帧图片的名字分别为Len_01.png,Len_02.png,Len_03.png,Len_04.png. sprintf(charBuffer,"Len_0%d.png",i+1); CCSpriteFrame *len_frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(charBuffer); len_AniFrames->addObject(len_frame); } //生成动画及动作. CCAnimation *len_ani = CCAnimation::animationWithSpriteFrames(len_AniFrames,0.2f); //创建精灵 CCSprite *len_sprite = CCSprite::spriteWithSpriteFrame((CCSpriteFrame*)len_AniFrames->objectAtIndex(0)); len_sprite->setPosition(ccp(size.width/2-30,size.height-50)); this->addChild(len_sprite,3); //执行动作 CCAnimate *len_animate = CCAnimate::actionWithAnimation(len_ani); len_sprite->runAction(CCRepeatForever::actionWithAction(len_animate)); len_AniFrames->release();
CCSpriteFrame *len_frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(charBuffer);可以通过plist中命名的每一帧图片的名字生成CCSpriteFrame 对象.至于每一帧的名字,大家可以自己打开plist文件去看.还有个更直观的方法就是在TexturePacker中右侧Sprites窗口中每个资源的名字,就是你每一帧图片的名字.
生成了每一帧的CCSpriteFrame对象就好办了,其他的都参照cocos2d-x系列笔记(4)---会动的小精灵一文中的代码就可以了.
左边黄头发的len就是我们用plist方式加载生成的精灵.