Creating and adding a FlxSprite in response to user input hangs my game!
-
Here's the gist of what I'm trying to do:
class PlayState extends FlxState { private function generatePiece():FungalPiece { return new FungalPiece(FungalPieceColor.Red, FungalPieceType.Single, this, 40, 64); } public function nextPiece():Void { var _nextPiece = generatePiece(); add(_nextPiece); } }
package; import flixel.FlxSprite; import flixel.FlxG; import flixel.math.FlxPoint; class FungalPiece extends FlxSprite { private var speed:Float = 200; private var _active:Bool = true; private var _playState:PlayState; public function new(color:FungalPieceColor, type:FungalPieceType, play:PlayState, ?X:Float=0, ?Y:Float=0, ?active:Bool=true) { super(X, Y); _active = active; _playState = play; // a bunch of code here to initialize the image } private function movement():Void { if (_active) { // move the piece code goes here if (_space) // if user presses the SPACE key { _active = false; _playState.nextPiece(); } } } }
When nextPiece() gets called, the current piece is locked, and a new piece is generated and is supposed to be added to the PlayState. This is causing the game to hang / freeze. There's got to be a "correct" way to do this; I just do not know what it is!
-
Are you sure you want all your pieces to divide in two, rather than just add one new piece?
Is_space
equal toFlxG.keys.pressed
orFlxG.keys.justPressed
?
-
I am checking for FlxG.keys.anyPressed([SPACE]) and setting the result to the _space variable.
Also, forgot to mention this earlier, but this game has a public GitHub repository, here. If anyone needs to look at full code, it's there.
-
anyPressed
fires every frame until key is released.anyJustPressed
fires once.
-
@wrldwzrd89 Ah, that makes a big difference when it comes to debugging this. :)
@starry-abyss While that's an issue, it's not what makes the game hang. It's actually not that intuitive.
So, what's going on here is:
- If space is pressedm,
FungalPiece
add()
s a newFungalPiece
instance to the state - it deactivates itself, but_active
of the new instance istrue
. - Since
add()
adds members to the end of themembers
array, and we're currently in the update loop, that newFungalPiece
instance from the previous step will be updated during the same frame - this means that space is still pressed (no matter if you're usingpressed
orjustPressed
)! It also starts out with_active = true
, so the code that spawns new instances will be executed again. So, jump to step 1 again - endless loop.
The easiest solution for this is probably to use
insert()
instead ofadd()
to add the new member at the start of themembers
list. That means newly spawned instances will only be updated next frame:insert(0, _nextPiece);
Btw, you don't need to declare an
_active
variable inFungalPiece
,FlxBasic
already has one that does pretty much the same thing.
- If space is pressedm,
-
A combination of using anyJustPressed and insert fixed things. Thanks!