Casting in Haxe



  • I've come across this code in a sample project. I'm a bit dumbfounded how this works.
    var bullet:FlxSprite = cast(cast(FlxG.state, PlayState).playerBullets.recycle(), FlxSprite);
    PlayState is a custom class containing playerBullets, how is it being casts to FlxG.state and why does it enable me to access an instance to a class I contain no reference to? Thanks, any help is appreciated.



  • I figured out the code. FlxG.state is a public variable, sitting in the game engine, it keeps track of the current state. So it's already instantiated, therefore when the person cast from state to PlayState it allowed the person to access the PlayState which is the current state.

    This is really dirty code.



  • Yeah, you should declare playerBullets as FlxTypedGroup<FlxSprite> or FlxTypedGroup<Bullet> (where bullet is derived from FlxSprite) and then pass either playerBullets or the function that does recycle() on it - to the object where it will be used. So there are no casts necessary

    The short version is: just forget you have FlxG.state and do the usual OOP


Log in to reply
 

Looks like your connection to HaxeFlixel was lost, please wait while we try to reconnect.