Search code examples
xcodeioscocos2d-iphoneactionccsprite

Control instances of specific CCSprites with separate class file in Cocos2d


I have just started working on my first cocos2d ios app.

I am very used to creating games in Game Maker, in which everything is simpler, and would like some help on creating separate .m/.h class files that contains functions that will affect all instances of a specific CCSprite. Obviously different class files for different CCSprites are needed.

In game maker, objects have code applied to them, and when i want something to happen when an instance is created its pretty easy, by just adding code to the create event.

In xcode i can't think how to do this.


Solution

  • One way to go would be to subclass CCSprite. Check out this guide for more info:

    http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:sprites

    Separate classes may also not be necessary, consider just having different initiators. Here is an example of a CCSprite subclass that can make both minions and evil rabbits:

    BadGuySprite *minion = [[BadGuySprite alloc] initAMinion];
    BadGuySprite *evilRabbit = [[BadGuySprite alloc] initAEvilRabbit];
    

    BadGuySprite.h

    #import "cocosd.h"
    
    @interface BadGuySprite: CCSprite
    {
       int lifebar;
    }
    
    +(id) initAMinion;
    +(id) initAEvilRabbit;
    
    @end
    

    BadGuySprite.m

    #import "BadGuySprite.h"
    
    @implementation BadGuySprite
    
    - (id)initAMinion{
            self = [CCSprite spriteWithFile:@"minion.png"];
            lifebar = 1000;
            return self;
    }
    - (id)initAEvilRabbit{
            self = [CCSprite spriteWithFile:@"rabbit.png"];
            lifebar = 1;
            return self;
        }
    
    @end