actionscript-3flixel

Why doesn't my custom FlxSprite appear on the stage?


I created a custom FlxSprite for a fireball by creating a new class(Fireball.as) and typing "extends FlxSprite" after the class name. In the constructor, it calls a function called "shoot()", which directs it to the target and plays a sound:

private function shoot():void {
    dx = target.x - x;
    dy = target.y - y;
    var norm:int = Math.sqrt(dx * dx + dy * dy);
    if (norm != 0) {
        dx *= (10 / norm);
        dy *= (10 / norm);
    }
    FlxG.play(soundShoot);
}


Then, I created an array to hold all the fireballs in the game state(PlayState.as):

public var fire:Array = new Array();


Then in my input() function, when someone pushes the mouse button, it pushes a new Fireball in the array:

if (FlxG.mouse.justPressed()) {
    fire.push(new Fireball(x, y, FlxG.mouse.x, FlxG.mouse.y));
}


But when I test it, it only plays the sound, but the fireball doesn't show up. I'm guessing that the fireball is somewhere offstage, but how do I fix it?

If it helps, here's the constructor for Fireball.as:

public function Fireball(x:Number, y:Number, tar_x:Number, tar_y:Number) {
    dx = 0;
    dy = 0;
    target = new FlxPoint(tar_x, tar_y);
    super(x, y, artFireball);
    shoot();
}

Solution

  • I think you must add them to stage.

    if (FlxG.mouse.justPressed()) {
        var fireball:Fireball = new Fireball(x, y, FlxG.mouse.x, FlxG.mouse.y);
        fire.push(fireball);
    
        // This line needs to be changed if you add the fireball to a group, 
        //  or if you add it to the stage from somewhere else
        add(fireball);
    }
    

    Let me know if it worked for you.