Question

I am trying to create array sprites which contain 5 sprites as 0.png, 1.png, 2.png, 3.png, 4.png.

I want them to appear randomly on the screen.

Below is my code but its not working, any help?

   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);
    }
Was it helpful?

Solution

Your "logic" currently is fine, it's the implementation that you have problem with.

If you check the initWithFile function, you see that it takes a file name as a string.

So you need to make an array of strings (the file names) and not an array of integers. Then you use the random index as index into this file-name array and pass it as argument to the initWithFile function.

OTHER TIPS

Ok, you are using the same code I provided you before:

 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.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top