Sprites/Textures being used in classes?

Sprites/Textures being used in classes?
0.0 0


So I have some trouble understand how this all works when I use the sprite/texture in a class and then use the sprite for the object (the class) in the GameScene.

In the tutorial, all that happens is you create a CCSprite * and use the spriteWithFile function.

        CCSprite *player = CCSprite::spriteWithFile("Player.png", 
                                                            CCRectMake(0, 0, 27, 40) );
        player->setPosition( ccp(player->getContentSize().width/2, winSize.height/2) );

But when I have my own class with a CCSprite * in the private portion, and am trying to set the sprite with the function above, I don’t think it works. Mainly because when I try to set the position of my CCSprite , I get the EXC_BAD_ACCESS error. This indicates that the pointer is faulty.
The way I’ve alleviated it before is I called new on it. But I don’t understand why I need to call new on this CCSprite
but not the one in the tutorial?

For instance, this is my code (I have an array of 6 CCSprite ’s and this is just setting the values for one of those CCSprite):

    m_vSprites[0]->setPosition(CCPoint(0, 0));

I could call new for the CCSprite , but I’d rather not have to do that every time I want to make a CCSprite in a class. If this is not possible, then I will, but I’d just rather not.

Also, speaking of the CCSprite *’s in the tutorial… when the game does the init() function and calls this~~>addChild, do I need to do this also in the GameScene’s init for my game except more using the object with the CCSprite *, like this~~>addChild(theObject->GetSprite()) or do I do the addChild in the object’s constructor/init function?

Any information would be great! Thanks!


You should retain it after you assign the pointer to your class member function, may be like this:

void assign(CCSprite *pSprite)
    if (m_pSprite)

    m_pSprite = pSprite;
    if (m_pSprite)


I’m not sure what part that is in reply to.

Is it in reply to me making a new CCSprite * to actually use the CCSprite *? Or is it in reply to my second question regarding when I add the child (the sprite to the scene)?


Making a new CCSprite* to actually use the CCSprite*.


Alrighty, well what about adding the CCSprite * from the class (the one I called new one to make it work with the CCSprite *), so it shows up on the scene?

I’ve got it working but it isn’t showing up on the screen. Not sure what’s going on with that.


So if I understand you correctly you want to make your own custom class that can create an object with Sprite?, if that’s the case check this tutorial from Raywenderlich(http://www.raywenderlich.com/782/harder-monsters-and-more-levels) and the converted cocos2d-x convertion of it here https://github.com/clawoo/SimpleGamePart3Cocos2D-x/tree/master/Classes.