I'm working on a simple Flash game for school. In one level, multiple enemies spawn and the player is supposed to shoot them. I used removeChild() to get rid of the enemy that got shot, but when I click (hit) an enemy, everything on my stage gets removed; it goes completely blank.
The function to populate my stage with enemies is the following:
private function Game2():void{
for (var i:uint=0; i<50; i++) {
var man:MovieClip = new man_mc();
man.x=Math.random()*750;
man.y=Math.floor(Math.random()*(70))+350;
addChild(man);
man.addEventListener(MouseEvent.CLICK开发者_开发问答, getroffen);
}
function 'getroffen' checks if an enemy got hit:
public function getroffen(evt:MouseEvent):void{
trace("hit");
this.parent.removeChild(this);
}
Kind of confused here as to why it removes everything on the stage instead of removing just the enemy I click on. Any help? Thanks alot.
depending on where getroffen()
is, you're removing that class (this
points to the current scope object), so I'm guessing it's probably the Main
class.
You need to do something like in your remove function:
var man:MovieClip = evt.target as MovieClip;
man.parent.removeChild( man );
Instead of this.parent.removeChild(this)
try:
evt.currentTarget.parent.removeChild(evt.currentTarget);
That should do the trick!
The event (mouseEvent) is a 'child' of one of your enemies, so removing the target of your mouseEvent will remove the enemy.
精彩评论