I made a little 2D shooter game for my iPhone. I want monsters to spawn at random locations. But I don't have any clue where to start to make them spawn.

I already made the monster image and everything and everything works, but there's only one monster at the start of the game and when it dies he will not spawn again.


1 Answer 1


Here is a thread on StackOverflow discussing random number generation in Objective-C. It's relatively straightforward: whenever it is time for a new monster to spawn, you generate two random numbers in a suitable range (for example, from 0 to the width or height of your playing field) and use those for the monster's initial X and Y location.

You can do whatever you want to determine "when it's time for a new monster to spawn," either by counting down with a timer (so new creatures spawn every five seconds regardless of whether or not the player has killed existing ones), or whatever you want.

It sounds like you're having trouble with the basics of getting the creature to respawn, so you should start with something simple: try checking at the beginning of every game loop if the monster is still alive. If he's not, create him. This should work both the first time the game starts and any subsequent iterations of the loop after the player kills the monster. For example, your code might look like:

MyMonster* monster = NULL;

// ...in your main game loop:
if(monster == NULL) {
   monster = /* create new monster */
   monster->X = randomNumberBetween(0, playfield.width);
   monster->Y = randomNumberBetween(0, playfield.height);

Note that the above is intended to be pseudo-code and will not compile or function exactly as-is. If you have trouble with the respawn, you should probably post another question about it (as it's a different question from picking random locations for a spawn position, and this is a Q&A site, not a forum).

  • \$\begingroup\$ Ok Thank you but i also want to know how i can spawn multiple monsters like in java you made one monster class and added it to the JPanel but i don't know how you could do this in Xcode \$\endgroup\$
    – jan
    Sep 16, 2011 at 15:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .