Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
How to do Object Pooling in Flixel
import flixel.FlxState;
import flixel.FlxSprite;
import flixel.util.FlxColor;
class PlayState extends FlxState {
//bullet group for holding player bullets
public var playerBulletGrp:FlxTypedGroup<FlxSprite>;
public static inline var PLAYER_BULLET_CAP:Int = 20;
override public function create() {
//Total amount of bullets the player can always have.
//In this case the player can only have 20 bullets.
playerBulletGrp = new FlxTypedGroup<FlxSprite>(PLAYER_BULLET_CAP);
//Initialize group with objects
for(i in 0...playerBulletGroup.maxSize) {
var bullet = new FlxSprite(0, 0);
bullet.makeGraphic(4, 4, FlxColor.WHITE);
override public function update(elapsed:Float) {
var fire = FlxG.keys.anyJustPressed([Z]);
if(fire) {
//Fire a bullet if the player hits the Z button
var bullet = playerBulletGrp.recycle(FlxSprite);
bullet.setPosition(100, 50);
bullet.velocity.set(300, 0);
for(bullet in playerBulletGrp) {
//Kills the bullet when it flys off screen so it can be reused later (object pooling)
if(!bullet.isOnScreen()) {

This comment has been minimized.

Copy link
Owner Author

@KinoAR KinoAR commented Apr 2, 2021

This is an example class that was written to demonstrate how the bullets would work with object pooling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment