Developers Manual > Cocos2d-x > How To > How To Create Sprites

How To Create Sprites

Sprites are a core element to any game. We need them. We often come to love the characters in games we make and play.

There are many ways to create Sprites API

1
cocos2d::Sprite* _mySprite = cocos2d::Sprite::create(); // empty sprite with no texture
1
cocos2d::Sprite* _mySprite = cocos2d::Sprite::create("mysprite.png"); 

What happens when you have a lot of sprites and you need to keep track of them? We need to use a data structure for this. What are our options? Array API or Vector API perhaps? If your needs are simple, the C++ STL also has array and vector containers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
std::vector<Sprite*> _vMySprites;
_vMySprites.reserve(5); // this may or may not make sense for your usage

for (int i=0;i < _vMySprites.capacity(); i++)
{
    cocos2d::Sprite* foo = cocos2d::Sprite::create("mysprite.png");

    int random = rand() % 5;

    foo->setPosition(cocos2d::Point((60 * random), (50 * random)));
    foo->setTag(i);

    _vMySprites.push_back(foo); // add our sprite to vector for storage.

    addChild(foo, 1);
}

Sign up for our newsletter to keep up with the latest developments, releases and updates for Cocos2d-x.