0

I have swords (consider them bullets) that the Hero throws, when it hits the tilemap the sword (bullet) is killed using kill() method. But unexpected thing happened. When using kill(), exists = false or visible = false ALL OF THE GROUP IS GONE (killed or invisible).
these are some snippets:

Sword.as(base class for all swords) shoot function :
public function shoot(playerPosition:FlxPoint, direction:uint):void{
  if(!alive || !exists){
    revive();
  }
  x = playerPosition.x;
  y = playerPosition.y;
  if(direction == FlxObject.RIGHT) {                
    angularVelocity = 900;
    velocity.x = 400;
  } else {
    angularVelocity = 900;
    velocity.x = -400;
  }
}

The subclass of Sword(BasicSword) has only sword graphics so it doesn't worth mentioning.

PlayState.as   
create (only part of it):       

for(var i:int = 0; i < 15;i++) {
  sword = new BasicSword(-200, -200);
  swords.add(sword);
}
add(swords);

Update:

override public function update():void{
  if(FlxG.keys.justPressed("X")) {
    (swords.recycle(BasicSword) as BasicSword).shoot(new FlxPoint(player.x,
      player.y),player.facing);
  }

  super.update();
  FlxG.collide(level, player);//make the player stand on the level.
  FlxG.collide(level, swords, swordsHitLevel);
}

swordsHitLevel(callback function):
public function swordsHitLevel(level:FlxTilemap, sword:FlxSprite):void {
  sword.kill();         
}
vyegorov
  • 21,787
  • 7
  • 59
  • 73
Abdulaziz
  • 2,201
  • 1
  • 21
  • 35

1 Answers1

0

This happens because you are checking collisions between the tilemap and the 'swords' group instead of the sword insance. This way, if any of the swords collides with the tilemap, then the swordsHitLevel is called for the group, not the individual sword

you might want to iterate through sword sprites

for(var sword:BasicSword in swords.children() ){
    FlxG.collide(level, sword, swordsHitLevel);
}

(code is not tested, I can give you a working snippet later if you need to)

EDIT : I fell into this issue myself today. Although I'm sure that the callback was called per member instead of FlxGroup, the collide function was returning false positives in some cases, but I didn't find out why or when. Could be a bug. I googled around and found this post. Ironically I had already answered that. So I worked around that. This time the code is tested and working

        for ( var i:int = 0; i < swords.members.length; i++ ) { 
            try{
                var sword:BasicSword= (BasicSword)(swords.members[i]);
                FlxG.collide(this.map, sword, swordsHitLevel);

            }catch (err:Error){}
        }   
yannicuLar
  • 3,083
  • 3
  • 32
  • 50