Reputation: 45
I'm looking to make many duplicates, or clones, of my CCSprite that's been subclassed. It's an enemy character in my game, and I will need to duplicate it countless times. How can I do this?
I've been told I should make an EnemyFactory class that makes the enemies in groups, and stores them for later levels in the game.
If someone could please explain this for me, that would be greatly appreciated :)
Upvotes: 0
Views: 3772
Reputation: 121
Sure, it sounds like you want a mechanism to track all the enemies you are creating, and watch/adjust their locations?
I suggest adding newly created enemies to a NSMutableArray like so:
static NSMutableArray *allMyEnemies = [[NSMutableArray alloc] init];
int numberOfEnemies = 3;
for (int i = 0; i < numberOfEnemies; i++){
EnemySpriteClass *enemy = [[EnemySpriteClass alloc] init];
[allMyEnemies addObject:enemy];
[self addChild:enemy];
}
Then when you want to look at/adjust the enemy sprite positions- say on the main game loop as they are attacking your hero, use the following:
for (int i = 0; i < [allMyEnemies count]; i++) {
EnemySpriteClass * obj = (EnemySpriteClass *)[allMyEnemies objectAtIndex:i];
NSLog("Enemy sprite is at this position: x:%f y:%f",
obj.position.x, obj.position.y);
//Then add logic to adjust that position if needed
obj.position.x -= 50;
}
Check out the official cocos2d forums for some good convience methods to do this kind of sprite management: http://www.cocos2d-iphone.org/forum/topic/5971
Upvotes: 3
Reputation: 1
Here is an example of what I use to create enemies.
Within your layer add the following when you want enemies to be created:
Gamelayer.m
int numberOfEnemies = 3;
for (int i = 0; i < numberOfEnemies; i++){
EnemySpriteClass *enemy = [[EnemySpriteClass alloc] init];
enemy.position = ccp(50 + 50*i, 50);
[self addChild:enemy];
}
And then create an enemey class based on CCSprite:
EnemySpriteClass.h
#import "cocos2d.h"
@interface EnemySpriteClass: CCSprite
{
}
-(id) init;
@end
EnemySpriteClass.m
#import "EnemySpriteClass.h"
@implementation EnemySpriteClass
-(id) init
{
if( (self=[super init] )) {
self = [CCSprite spriteWithFile:@"squid.png"];
//Add AI, life other properties.
}
return self;
}
If your having performance issues creating them on the fly, you can always batch create them and then call [self addchild:enemy] when you want them on screen.
Upvotes: 0