How to duplicate a Sprite and set each of them in random position?

I am trying to generate platforms with different levels and positions, this is the code I could come up with, but it seems to only display one platform.

#include "BushScene.h"
#include "MainScene.h"
#include "cocos2d.h"
Size size;

bool BushScene::init() {

size = Director::getInstance()->getWinSize();

  bool bret = false;

    do{

    		MainScene::init();

    		CC_BREAK_IF(! Layer::init());


    		initPlatforms();

    		bret = true;
    }while(0);

return bret;

}

void BushScene::initPlatforms(){ Sprite* plats = Sprite::create("platform.PNG"); int i = 0; while(i < platformCount){ i++; platforms.pushBack(plats); } setPlatforms(); }

void BushScene::setPlatforms(){ platformTag = 0; for(int i = 0; i < 50; i++){ platformTag = i; for(Sprite* &platform : platforms){ float x = rand() % (int)(Director::getInstance()->getVisibleOrigin().x + Director::getInstance()->getVisibleSize().width/2); float y = rand() % (int)(Director::getInstance()->getVisibleOrigin().y + Director::getInstance()->getVisibleSize().height/2); CCLog("set X %d", x); CCLog("set Y %d", y); platform->setPosition(ccp(x, y)); CCLog("addChild %d, platformTag %d", (Sprite*)getChildByTag(platformTag), platformTag); this->addChild(platform, 3, platformTag); } } //resetPlatform(); }

I don’t see where you set the position. You calculate y and x but don’t use them.
:wink:

sorry, i didn’t paste the code properly. Markdown issues. I’ll update the code.

Please take a look again :smile:

Well, you create only one sprite, you don’t clone it, you just reposition it again and again.

how do i clone it? I already pushed them into a Vector, and what i am trying to do is I call loop through the vector and display each

Yeah, but the vector always points to the same Sprite.
You have to put Sprite::create("platform.PNG") inside the loop.
For example like this
platforms.pushBack(Sprite::create("platform.PNG"));

Thanks Maus, I have found an algorithm that duplicates a sprite on this thread. It has worked :smiley: [done] How to reuse CCSprite?

It seems to be a bit of an overload in your case. You have no children in your sprite…

But if it works for you…
:wink: