functor functor - 3 months ago 23
C++ Question

Cocos2D Image Storage

I'm developing a game in Cocos2D (cocos2d-x-3.12) and I'm wondering which data structure I should use to store images; I need this because I'm defining a class which has several states (each state with its own separate image) and don't want to load image from the file on every state change. (I guess reading from file affects performance)

Since my class is derived from Sprite, I checked Sprite's member functions to change its image and I found the following:


  • Sprite::setTexture() which receives either filename or a Texture2D

  • Sprite::setSpriteFrame() which receives either name or a SpriteFrame



I already tried Texture2D like this:

auto img = new Image();
img->initWithImageFile("blah.png");
auto txtr = new Texture2D();
txtr->initWithImage(img);
sprite->setTexture(txtr);


But it doesn't work. So I'm left with SpriteFrame option:

auto img = new Image();
img->initWithImageFile("blah.png");
auto frame = SpriteFrame::create("blah.png", Rect (0, 0, img->getWidth(), img->getHeight()));
sprite->setSpriteFrame(frame);


This actually works but I can't find out how the Rect part works. It also affects positioning. Like the below example which is supposed to put the image on the center of the screen:

auto img = new Image;
string fileAddr = "HelloWorld.png";
img->initWithImageFile(fileAddr);
auto sprite = Sprite::create();
auto frame = SpriteFrame::create(fileAddr, Rect (0, 0, img->getWidth(), img->getHeight()));
sprite->setSpriteFrame(frame);

// position the sprite on the center of the screen
sprite->setAnchorPoint(Vec2 (0.5, 0.5));
sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));


But results in: Test Run #1

And using:

sprite->setAnchorPoint(Vec2::ZERO);


The result looks like: Test Run #2

Any help would be appreciated! :)
Thanks...

Answer

You can just use Sprite::setTexture(const std::string &filename) to change your texture of sprite. Because a texture will be cached by TextureCache (you can a) singleton once you use it. If you want to load texture before use it to get higher performance, you can load the texture by TextureCache::addImage(const std::string &filepath).