Catlin Kash Claybert
Catlin Kash Claybert

Reputation: 38

Cocos2D calling an object init from a scene layer init

Hi I'm currently working on an iPhone game, top-down Strategy RPG (kinda like Fire Emblem), I have my tiled map set up, and the gameplay layer and some characters and enemies set up and drawn on the screen and moving around. My question really just to help wrap my head around how I can initialize my characters easliy. My character init is simple, it just loads the animations and set the stats as such:

//Hero Class

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

        [self initAnimations];

        [self declarePlayer:Hero withLevel:1 withStrength:15 withDefence:14 withMindpower:15 withSpeed:26 withAgility:26 withLuck:12 withEndurance:10 withIntelligence:15 withElement:kFire withStatus:kStatusNormal];
    }

    return self;
}

and so in the game scene, can I just be like:

(in .h file)

PlayerCharacter *mainChar;
@property(retain)PlayerCharacter *mainChar;

(in .m file)

-(id) init
{
    if((self=[super init]))
    {
        //the usual stuff
        mainChar = [MainCharacter init];

        return self;

    }
}

However, I've seen online and in tutorials people using

MainCharacter *mainChar = [MainCharacter alloc];

would that be the same as

mainChar = [MainCharacter init];

if not could someone help clarify which syntax to use. Thanks very much :D Have a great day!

Upvotes: 0

Views: 391

Answers (1)

Aram Kocharyan
Aram Kocharyan

Reputation: 20421

I think you should consider reading quickly through some introduction tutorials. This one is awesome and will get you used to the syntax and semantics of Objective-C:

http://cocoadevcentral.com/d/learn_objectivec/

alloc will allocate memory for an object and init will set things up like a regular constructor. You will also see initWith... style functions which can also be used like so:

MyObjectClass *instance = [[MyObjectClass alloc] init];

This then needs to be released in the same class it was created in the dealloc method.

As for setting up objects, it's better to not use a really long method name declarePlayer:Hero withLevel... but rather:

Set up the object and then alter properties:

Player *player = [[Player alloc] init];
player.health = 10;
player.armor = 20;
...

Once you become familiar with Objective-C as a language, tacking cocos2d and any other code will be much easier. For that, you can visit the the programming guide and find tutorials around the web like at www.learn-cocos2d.com.

Upvotes: 1

Related Questions