Search code examples
iosxcodecocos2d-iphonesubclassccsprite

Adding a subclass of CCSprite to a scene


I've recently decided to subclass my sprite, but I am a bit clueless on how to add them to a scene. At the moment, I have created my CCSprite subclass, using New File>Cocos2d>CCNode>Subclass of... CCSprite. Then, I have made my sprite in the Sprite.h file:

@interface Mos : CCSprite {
    CCSprite *mos;
}

Once this is done, in the Sprite.m I code this:

@implementation Mos

-(id) init
{
    if( (self=[super init])) {

        mos = [CCSprite spriteWithFile:@"sprite_mos.png"];

    }
    return self;
}

What I want to know is how to then add this sprite into my game's scene.


Solution

  • Here is how to correctly subclass CCSprite as the documentation says:

    @interface Mos : CCSprite {
        // remove the line CCSprite *mos;
    }
    
    @implementation Mos
    
    // You probably don't need to override this method if you will not add other code inside of it
    -(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect
    {
       if( (self=[super initWithTexture:texture rect:rect]))
       {
    
       }
       return self;
    }
    
    + (id)sprite
    {
        return [Mos spriteWithFile:@"sprite_mos.png"];
    }
    
    @end
    

    Then in your code, you can use Mos normally:

    Mos *mos = [Mos sprite];
    [scene addChild:mos];