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.

  • \$\begingroup\$ Is the spawning going to be dependent on some event or is it just time based? \$\endgroup\$
    – House
    Sep 18 '13 at 15:01
  • \$\begingroup\$ It's going to be dependent on some event (FlxG.score). :) \$\endgroup\$
    – teddyweedy
    Sep 19 '13 at 11:38
  • \$\begingroup\$ I think I've already answered my question. Case closed. Still, thanks for your reply, Byte56. :) \$\endgroup\$
    – teddyweedy
    Sep 19 '13 at 13:30

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;
        player.acceleration.x = -player.maxVelocity.x*4;
        player.acceleration.x = player.maxVelocity.x*4;
    if(FlxG.keys.SPACE && player.isTouching(FlxObject.FLOOR))
        player.velocity.y = -player.maxVelocity.y/2;



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) {

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:

if (score == 1) {
  // Spawn a bad guy next frame.

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.

  • \$\begingroup\$ Here is a chapter on the observer pattern specific to game development. \$\endgroup\$
    – lozzajp
    Feb 16 '17 at 9:24

You must log in to answer this question.

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