我正在创建一系列精灵,它们应该随机出现,但它发生了

I am creating array of sprites and they should appare randomly but its happening?

本文关键字:随机 发生了 一系列 创建 精灵      更新时间:2023-10-16

我正在尝试创建包含5个精灵的数组精灵,如0.png, 1.png, 2.png, 3.png, 4.png

我希望它们随机出现在屏幕上。

下面是我的代码,但它不工作,任何帮助?

   std::vector <CCSprite*> _sprites;
   _sprites.reserve(10); 
    int spritearray[5] = { 0.png,1.png,2.png,3.png,4.png }; // I AM GETTING ERROR HERE?
     int i;
    for(i=0;i<5;i++)
    {
        CCSprite* foo = new cocos2d::CCSprite();
       int index = rand() % 5;
       // foo->initWithFile(index);
        foo->setPosition(ccp(60,50*i));
        _sprites.push_back(foo); //store our sprites to do other stuffs later
        this->addChild(foo,1);
    }

你的"逻辑"目前是好的,这是你有问题的实现。

如果您检查initWithFile函数,您会看到它接受文件名作为字符串

所以你需要创建一个字符串数组(文件名),而不是整数数组。然后使用随机索引作为该文件名数组的索引,并将其作为参数传递给initWithFile函数。

好的,您使用的是我之前提供给您的相同代码:

 std::vector <CCSprite*> _sprites;
_sprites.reserve(10); 
std::vector<std::string> _spriteNames = {"0.png", "1.png", "2.png", "3.png", "4.png"};
for (int i=0;i < _spriteNames.size(); i++)
{
   CCSprite* foo = cocos2d::CCSprite::create(_spriteNames.at(i));
    int random = rand() % 5;
    foo->setPosition(CCPoint((60 * random), (50 * random)));
    _sprites.push_back(foo); // <- store your sprites to do stuff to them later.
   addChild(foo, 1); //<-- this is adding the child.
}