0
votes

I am just now trying to show sprite on stage using CCSprite.

The character class is a class which has succeeded to the CCSprite.

I wrote the code as following:

bool HellowWorld::init() method:

bool HelloWorld::init()
{

int Indexes[9] = {5,11,15,16,17,19,20,21,25};
int x;
int y;
CCArray *filename = new CCArray();



filename->addObject(new CCString("1-1.png"));
filename->addObject(new CCString("2-1.png"));
filename->addObject(new CCString("1-2.png"));
filename->addObject(new CCString("2-3.png"));
filename->addObject(new CCString("2-3.png"));
filename->addObject(new CCString("1-2.png"));
filename->addObject(new CCString("2-3.png"));
filename->addObject(new CCString("1-1.png"));
filename->addObject(new CCString("1-1.png"));




for(int i=0;i<9;i++){

    const char *MyImage = ((CCString*)filename->objectAtIndex(i))->getCString();
    characters *chara = (characters*)CCSprite::create(MyImage);

    x = Indexes[i]%HORIZONTAL_AXIS;
    y = Indexes[i]/HORIZONTAL_AXIS;


    CCPoint point = ccp(MARGIN_WIDTH + PIPE_WIDTH * x,MARGIN_HEIGHT + PIPE_HEIGHT * y);
    chara->setPosition(point);


    this->addChild(chara,1);


}

But, I am getting the following error message:

libc++abi.dylib: terminating with uncaught exception of type std::length_error: basic_string::_S_create

How should I solve this issue?

1
Thank you for your comment. If I don't cast,the error appear as follow. 「Cannot initialize a variable of type 'Characters *'with an rvalue of type 'cocos2d::CCSprite *」 - user3321541
that's because you are creating a sprite, not a character instance - LearnCocos2D

1 Answers

0
votes

There are definitely some coding issues here.

const char *MyImage = ((CCString*)filename->objectAtIndex(i))->getCString();
characters *chara = (characters*)CCSprite::create(MyImage);

You are doing a lot of casting and it is confusing. Your cast to (characters*) is just wrong.

  1. characters seems like it needs to subclass CCSprite*, I hope that it does.

  2. then you can do something like:

    characters *chara = characters::create(filename->objectAtIndex(i)->getValue());

  3. If your for loop you have a hardcoded 9. You might change that to filename->count() that way it always loops to the size of the CCArray.

Here is the docs for CCSprite: http://www.cocos2d-x.org/reference/native-cpp/V2.2.3/d8/de9/group__sprite__nodes.html#ga0e84a5bd213dc1556503a4120243a390