【问题标题】:Cocos2D Image StorageCocos2D 图像存储
【发布时间】:2016-08-27 13:52:20
【问题描述】:

我正在用 Cocos2D (cocos2d-x-3.12) 开发一个游戏,我想知道应该使用哪种数据结构来存储图像;我需要这个,因为我正在定义一个具有多个状态的类(每个状态都有自己的单独图像)并且不想在每次状态更改时从文件中加载图像。 (我猜从文件中读取会影响性能)

由于我的类是从 Sprite 派生的,所以我检查了 Sprite 的成员函数以更改其图像,发现如下:

  • Sprite::setTexture() 接收文件名或 Texture2D
  • Sprite::setSpriteFrame() 接收名称或 SpriteFrame

我已经尝试过这样的 Texture2D:

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

但它不起作用。所以我留下了 SpriteFrame 选项:

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

这确实有效,但我不知道 Rect 部分是如何工作的。它也会影响定位。就像下面的例子一样,它应该把图像放在屏幕的中心:

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));

但结果是:Test Run #1

并使用:

sprite->setAnchorPoint(Vec2::ZERO);

结果如下:Test Run #2

任何帮助将不胜感激! :) 谢谢...

【问题讨论】:

    标签: c++ cocos2d-x


    【解决方案1】:

    你可以使用Sprite::setTexture(const std::string &filename) 来改变你的精灵纹理。因为纹理一旦使用就会被TextureCache单例缓存。如果你想在使用前加载纹理以获得更高的性能,可以通过TextureCache::addImage(const std::string &filepath)加载纹理。

    【讨论】:

      【解决方案2】:

      你可以这样存储 SpriteFrame:

      auto frame = Sprite::create("blah.png")->getSpriteFrame();
      

      你也可以使用 TextureCache(就像 SparkJay 说的)或 SpriteCache。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-07
        • 1970-01-01
        • 2011-04-21
        • 2016-07-22
        • 1970-01-01
        相关资源
        最近更新 更多