大佬教程收集整理的这篇文章主要介绍了cocos2d-x中的精灵类,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
在cocos2d-x中,精灵处理有关的类共有4个:
精灵类CCSprite、精灵批处理类CCSpriteBatchNode、精灵帧类CCSpriteFrame和精灵帧缓存类CCSpriteFrameCache
在精灵类CCSprite中,创建精灵的方式有:
static Sprite* create(const std::String& fileName);
static Sprite* createWithTexture(Texture2D *texturE);
static Sprite* createWithSpriteFrame(SpriteFrame *spriteFramE);
static Sprite* createWithSpriteFramename(const std::String& spriteFrameName);
第一个函数是利用图片文件的文件名,第二个是利用图片纹理信息创建精灵,第三和第四个是利用精灵帧和精灵帧名来创建函数。通过查看各个函数的源代码可以发现,这四个函数最终都会进入函数
bool Sprite::initWithTexture(Texture2D *texture,const Rect& rect,bool rotated)
实际上这四个方法最终都是利用图像的纹理信息来创建精灵。
精灵批处理类CCSpriteBatchNode:它可以一次性渲染多副图像,可以降低图像渲染的次数,防止渲染次数过多造成的延时。
CCSpriteBatchNode* batchNode = CCSpriteBatchNode::create("black.png",1000);
batchNode->setPosition(CCPointZero);
this->addChild(batchNodE);
for (int i = 0; i<1000; ++i){
float x = CCRANDOM_0_1()*visibleSize.width;
float y = CCRANDOM_0_1()*visibleSize.height;
CCSprite* testIcon = CCSprite::createWithTexture(batchNode->getTexture());
testIcon->setPosition(ccp(x,y));
batchNode->addChild(testIcon);
}
效果图如下:
精灵帧类CCSpriteFrame构造的对象可以是图像的某一部分,可以通过构造一系列精灵帧对象形成动画,常与精灵帧缓存类CCSpriteFrameCache一起使用来形成动画。
精灵帧缓存类CCSpriteFrameCache使用单例模式,通过读入plist文件来快速加载精灵帧,plist文件记录了每幅图像在合成的大图像中的信息,这样可以一次渲染多幅图像。
CCSpriteFrameCache * cache = CCSpriteFrameCache::sharedSpriteFrameCache();
cache->addSpriteFramesWithFile("ghosts.plist");
//利用plist文件中的图片信息可以一次渲染所有图片
char str[20] = { 0 };
for (int i =1; i<=4; ++i){
float x = CCRANDOM_0_1()*visibleSize.width;
float y = CCRANDOM_0_1()*visibleSize.height;
sprintf(str,"icon%d.gif",i);
CCSprite *sp = CCSprite::createWithSpriteFramename(str);
sp->setPosition(x,y);
this->addChild(sp);
}
效果图如下:
该类还可以得到一系列图片构成的一组精灵帧,利用这些精灵帧和CCAnimation类中的函数可以形成动画。
Vector< SpriteFrame* > sfme = Vector< SpriteFrame* >::Vector(4);
char str[20] = {0};
for( int i = 1 ; i <=4 ; ++i )
{
sprintf(str,i);
SpriteFrame *fname = cache -> spriteFrameByName( str );
sfme.pushBACk( fname );
}
CCAnimation *animation = CCAnimation::createWithSpriteFrames( sfme,0.05f );
sp -> runAction ( CCAnimate::create(animation ));
以上是大佬教程为你收集整理的cocos2d-x中的精灵类全部内容,希望文章能够帮你解决cocos2d-x中的精灵类所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。