Generate array of sprites (Cocos2dx, C++, Android)

Posted on Updated on

alright before i forget i better write this down (being an idiot that i am i’ll forget this later)

i have this image:

which when fired at, a single block explodes gracefully like a new born baby taking its first breath outside of a womans-anyway having 1 massive image like the one above to hold several dozen block images isn’t a good idea.

A better way to do this is to have each block:

stored in an array or vector, loop over then before the loop is finished, add each element into our layer.

In code this would look something like this:

Block header file .h

#ifndef __BLOCK_H__
#define __BLOCK_H__
#include "cocos2d.h"
class Block : public cocos2d::Sprite
// ....
    Sprite*                 block;
    Block();                                                    //  constructor
    Sprite*                 generateBlock(int pos);             //  generate a block
#endif // __BLOCK_H__

Block Implementation file.cpp

// ... 
Sprite* Block::generateBlock(int pos) {
    Block        _block_obj;            // instantiate our block class
// ...
    block      = Sprite::create("block.png");
    block     -> setPosition(Vec2(visibleSize.width/2 + pos, visibleSize.height));
    return block;
// ...

Now in our game scene we can do something like this:

Game scene header file.h

// ...
std::array<cocos2d::Sprite*, 10> _blockArray;
void    generateBlocksThenAddToArray();                              // generate a block then add into our array
// ...

implementation file .cpp

 *  generate a block then add into our array
void Hoge::generateBlocksThenAddToArray() {
    for (int i = 0; i < 10; i++) {
        Sprite* _generatedBlock  = _block_obj.generateBlock((i * 100) / 2);
        _blockArray[i]        = _generatedBlock;
        this                 -> addChild(_generatedBlock);

The magic happens in the for loop in Hoge::generateBlocksThenAddToArray() method.
We loop to a suitable range (10 in this case),generate a block from the block class, set its x position by multiplying it by 100 per iteration using i, then add the instantiated block object into our _blockArray with the loop count as its address, then finally add the generated block into our game scene.

There’s probably another (better) way to do this, and I’d love some input from other talented programmers out there so, please give me a shout in the comment section below!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s