HaxeFlixel Logo HaxeFlixel Snippets
  • About
  • Tutorials
  • Back to HaxeFlixel.com
  • Basics
    • Screen
    • Adding
  • Objects
    • Alive
    • Health
  • Sprites
    • Making Sprites
    • Loading Sprites
    • Animation
    • Alpha
    • Color
    • Facing
    • Scale
    • Baked Rotations
  • Text
    • FlxText
    • FlxBitmapText
  • Movement
    • Velocity
    • Acceleration
    • MaxVelocity
    • Gravity
    • Jumping
    • Angle
    • Angular Velocity
    • Angular Acceleration
  • Groups
    • Basic Group
    • Typed Group
    • Recycling
  • Tiling
    • Tileblock
    • Tilemap
  • Overlap
    • Simple Overlap
    • Overlap Callbacks
  • Collision
    • 1-to-1 Collision
    • Immovable
    • Tilemap Collision
    • Moving Platforms
  • Camera
    • Flash
    • Fade
    • Shake
    • Follow
  • Input
    • Basics
    • Keyboard
    • Mouse
    • Button
  • Sound
    • FlxSound

Recycling

One of the more powerful aspects of groups is FlxTypedGroup.recycle().

// revive the next dead object in the group,
// or create a new one if we haven't reached maxSize
sprite = group.recycle(Sprite.new);

This is very useful for things like bullets, particles, enemy spawns, etc, where you don’t want to call new() frequently.

Note: FlxTypedGroup.recycle() will act differently depending on if the group has a maxSize defined or not.

Demonstration

Source

source/PlayState.hx

package;

import flixel.FlxG;
import flixel.FlxState;
import flixel.group.FlxGroup.FlxTypedGroup;

class PlayState extends FlxState
{
    var group:FlxTypedGroup<Sprite>;
    var spawnTimer:Float = 0;

    override public function create()
    {
        super.create();

        add(group = new FlxTypedGroup<Sprite>(20));
    }

    override public function update(elapsed:Float)
    {
        spawnTimer += elapsed * 5;
        if (spawnTimer > 1)
        {
            spawnTimer--;
            group.add(group.recycle(Sprite.new));
        }

        super.update(elapsed);
    }
}

source/Sprite.hx

package;

import flixel.FlxG;
import flixel.FlxSprite;
import flixel.system.FlxAssets.FlxGraphicAsset;

class Sprite extends FlxSprite
{
    public function new()
    {
        super("assets/sprite.png");
        kill();
    }

    override public function revive()
    {
        x = -width;
        y = FlxG.random.int(0, Std.int(FlxG.height - height));
        velocity.x = 200;
        super.revive();
    }

    override public function update(elapsed:Float)
    {
        if (x > FlxG.width)
            kill();
        super.update(elapsed);
    }
}
View Source on GitHub

Tags

groups
  1. Home
  2. Groups
  3. Recycling
Powered By HaxeFlixel Logo HaxeFlixel