# How can I spawn multiple monsters in my game?

I made a little iPhone game in which I want to make multiple monsters spawn.

I have one UIImageView called enemy that spawns at beginning of the game. But I want it to spawn many more monsters until I say it needs to stop spawning them.

I know how to get random locations. This question is a follow up to this one.

• I'm not sure but there sould be some timer class somewhere in iphone sdk – Ali1S232 Sep 16 '11 at 19:02

You need to have a collection of monsters and a MAX_MONSTERS constant. I'm not much of an Objective-C programmer, but this pseudo-code should get you going:

.. top of program
MAX_MONSTERS = 5;
MonsterCollection[MAX_MONSTERS] mc;

... game loop
for(int i = 0; i < MAX_MONSTERS; i++)
if(mc[i] != null && mc[i].IsAlive)
mc[i].Update();
else
mc[i] = // new monster

• okay thank you but i mainly want to know how i can add more monsters like i have one uiimageview called enemy and i want to have 5 enemy's on screen but not declare everything 5 times – jan Sep 16 '11 at 20:47
• You can use an array, to declare one time, that you want a variable number of monsters. Otherwise you'll need to declare n different UIImageView objects, where n is the number of monsters you want. – Nate Sep 16 '11 at 21:07
• so i need to create an array called monsters that stores as much variables as need and all those variables are the same UIImageView? – jan Sep 16 '11 at 21:55

From your question it seems like the UIImageView is holding your monster-graphics. The more important thing however is where you located the monster-logic (that will update/move the monster-graphics).

For multiple monsters, you'll need multiple instances of the UIImageView. Also you'll need to keep track of position and other properties (like health) for each monster. A reasonable approach to this would be to have a separate class that encapsulates all monster related logic.

Therefore, I suggest you create a special class (that inherits from NSObject) for monster and make the UIImageView a member of this class. A really basic interface for such a class could look like this:

#import <Foundation/Foundation.h>

@interface Monster : NSObject {

}

@property(retain) UIImageView* view;

-(void) update:(double)dt;

@end


In the init method of your monster-class you would initialize your graphics (and assign it to the view property). Creating multiple monsters can be done using something like this:

// constant that defines how many monsters should be created
#define NUM_MONSTERS 5

// monsters should be a member of your class, so that you can loop through it
// and perform updates. This is why we "retain" the monsters array here.
// You should use "release" to free the array in the class dealloc method.
NSMutableArray* monsters =
[[NSMutableArray arrayWithCapacity:NUM_MONSTERS] retain];

for(int i = 0; i < NUM_MONSTERS; ++i){
Monster* monster = [[Monster alloc] init];
// store the monster in the monsters array