龙图教育:cocos2dx之精灵类Sprite使用方法

Image * image = nullptr ; image = new Image ( ) ;

CC_BREAK_IF ( nullptr == image ) ;

bool bRet = image -> initWithImageFile ( fullpath ) ; CC_BREAK_IF ( ! bRet ) ; texture = new Texture2D ( ) ;

if ( texture && texture -> initWithImage ( image ) ) {

// Do something... }

在后面一会还会总结到关于 Texture2D 的缓存,在工作中,我们使用缓冲更多一些。继续吧。

SpriteBatchNode

当我们需要显示多个同样的精灵对象时,如果逐个渲染精灵,每一次渲染都会调用OpenGL的函数,每次渲染都是有一定的性能开销的,这样就导致了性能下降。如果将所有需要渲染的同一张贴图只进行一次准备,一次渲染,一次清理就可以解决这个问题了。 SpriteBatchNode 类就可以批处理这些精灵。

有的时候,在做射击类游戏的时候,屏幕上会存在很多由玩家射出的子弹,而这些子弹都是同样的精灵,我们就可以使用 SpriteBatchNode 来实现。

加入的 SpriteBatchNode 类的精灵类越多,提高效率的效果就越明显。下面就通过代码,来看看如何添加 SpriteBatchNode 类的精灵。

SpriteBatchNode * batchNode = SpriteBatchNode :: create (\ormal.png\

batchNode -> setPosition ( CCPointZero ) ; this -> addChild ( batchNode ) ; for ( int i = 0 ; i < 1000 ; ++ i ) {

int x = rand ( ) % 960 ; int y = rand ( ) % 640 ;

Sprite * testIcon = Sprite :: createWithTexture ( batchNode -> getTexture ( ) ) ; testIcon -> setPosition ( ccp ( x , y ) ) ; batchNode -> addChild ( testIcon ) ; }

上面是使用的 SpriteBatchNode 来提高的游戏性能。我在电脑模拟器上进行了试验,但是并没有实际的效果,对于这点,确实不是很明白。以下是不使用SpriteBatchNode 的代码:

for ( int i = 0 ; i < 1000 ; ++ i ) {

int x = rand ( ) % 960 ; int y = rand ( ) % 640 ;

Sprite * testIcon = Sprite :: create ( \testIcon -> setPosition ( ccp ( x , y ) ) ; this -> addChild ( testIcon ) ; }

我在这里求解。 SpriteFrame

SpriteFrame 也就是精灵帧的概念。精灵帧这个是相对于动画而产生的。一个精灵是一张二维图片,如果一个精灵具有动画效果。我们使用程序进行控制,使精灵在不同的二维图片之间进行切换,这样就形成了动画效果。先来看看创建SpriteFrame 的函数。

static SpriteFrame * create ( const std :: string & filename , const Rect & rect ) ; static SpriteFrame * create ( const std :: string & filename , const Rect & rect , boolrotated , const Vec2 & offset , const Size & originalSize ) ;

static SpriteFrame * createWithTexture ( Texture2D * pobTexture , const Rect & rec

t );

static SpriteFrame * createWithTexture ( Texture2D * pobTexture , const Rect & rect ,bool rotated , const Vec2 & offset , const Size & originalSize ) ;

这些创建函数的参数已经熟悉的不能再熟悉了,这里不做讲解了。我们主要是将

SpriteFrame 添加到 Animation 生成动画数据,关于Cocos2d-x中的动画,后续还会总结,这里就先不说了。 SpriteFrameCache

精灵帧缓存类 SpriteFrameCache 用来存储精灵帧,提前缓存起来有助于提高程序的效率。 SpriteFrameCache 是一个单例模式实现的,它不属于某个精灵,而是所有精灵共享使用的。

我们可以向缓存中添加精灵帧,同时,也可以手动删除指定的,或者没有使用的精灵帧。具体的函数,可以参考 SpriteFrameCache 的定义。 总结

一般使用 Texture2D 加载图片,使用 Texture2D 生成对应的 SpriteFrame(精灵帧), SpriteFrame 添加到 Animation 生成动画数据,用 Animation 生成 Animate (就是最终的动画动作),最后用 Sprite 执行这个动作。

联系客服:779662525#qq.com(#替换为@) 苏ICP备20003344号-4