# How can I spawn a sprite based on a condition after the game starts?

How do I spawn a sprite anytime later in the game when the game starts?

I'm using FlashDevelop with Flixel. I did try it in override public function create(): void. It works only in the beginning. I try it using if (FlxG.score == 1) but it doesn't work. I also tried it in override public function update(): void. It works and it is moving but it leaves a sprite making it a multi-sprite. I also did try FlxGroup but to no avail.

• Is the spawning going to be dependent on some event or is it just time based?
– House
Sep 18 '13 at 15:01
• It's going to be dependent on some event (FlxG.score). :) Sep 19 '13 at 11:38

Spawn the sprite when the appropriate event or conditions for spawning are met.

Flixel gives you an update method that runs periodically. For example, in the Flixel platformer tutorial, the update method is overridden thusly:

override public function update():void
{
player.acceleration.x = 0;
if(FlxG.keys.LEFT)
player.acceleration.x = -player.maxVelocity.x*4;
if(FlxG.keys.RIGHT)
player.acceleration.x = player.maxVelocity.x*4;
if(FlxG.keys.SPACE && player.isTouching(FlxObject.FLOOR))
player.velocity.y = -player.maxVelocity.y/2;

super.update();

FlxG.collide(level,player);
}


One (of many potential) ways to handle spawning on some condition is to check for that condition during the periodic update and spawn creatures as needed. Of course, you can't just check for the condition directly (for example, doing if (score == 1) spawn() in the update loop would spawn a new enemy every frame that the score is still 1, which probably isn't what you want).

Instead, consider storing information about what you need to do during the update. If your game object had an integer field for enemySpawnsThisFrame, you could do something like:

while (enemySpawnsThisFrame > 0) {
spawn();
--enemySpawnsThisFrame;
}


Then, when an event occurs that should trigger a spawn on the next frame update, you simply increment this counter. For example, in the code where you increment the score:

++score;
if (score == 1) {
// Spawn a bad guy next frame.
++enemySpawnsThisFrame;
}


This should get you off the ground. As your project grows, this kind of tight coupling between systems becomes very undesirable, because it increases the difficulty of maintenance. To avoid this, you can implement some kind of observer pattern to isolate dependencies. In such a world, incrementing the score would raise a "score incremented" event. External systems (like the game itself) interested could subscribe to that event and set up the enemy spawn.

• Here is a chapter on the observer pattern specific to game development. Feb 16 '17 at 9:24