Hello,
I’m having trouble removing a child that I have spawned from an array. If I try to use the same for each loop that I use to address the children in the array in other functions, it removes all children that are in the array, but if I try to remove only that child, it complains the child is null.
The clickListener function is working out if the crosshairs are on the cow when the mouse clicks, but I want to wait two seconds (to allow the death animation to play in the clicked cow) before removing the child.
Here’s what I’m doing:
package {
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.*;
import flash.ui.Mouse;
public class CowGame extends MovieClip {
public var herd:Array;
public var cow:Cow;
public var gameTimer: Timer;
public var deathDelay: Timer;
public var crossHairs: CrossHairs;
public var gunShot: GunShot;
public var moo: Moo;
public function CowGame() {
Mouse.hide();
herd = new Array();
for (var i:int = 0; i<10; i++) {
var randomX:Number = 800 + Math.random()*800;
var randomY:Number = 200 + Math.random()*400;
var cow = new Cow(randomX, randomY);
herd.push(cow);
addChild(cow);
}
crossHairs = new CrossHairs();
addChild(crossHairs);
stage.addEventListener(MouseEvent.CLICK, clickListener);
gameTimer = new Timer(25);
gameTimer.addEventListener(TimerEvent.TIMER, timeKeeper);
gameTimer.start();
}
public function timeKeeper(timerEvent:TimerEvent):void {
crossHairs.x = mouseX;
crossHairs.y = mouseY;
for each (var cow:Cow in herd) {
cow.moveCow();
}
timerEvent.updateAfterEvent();
}
public function clickListener(e:MouseEvent):void {
//trace(e);
for each (var cow:Cow in herd) {
if (crossHairs.hitTestObject(cow)) {
if (cow.alive) {
cow.alive = false;
gunShot = new GunShot();
gunShot.play();
moo = new Moo();
moo.play();
cow.gotoAndStop("shot");
deathDelay = new Timer(200, 1);
deathDelay.addEventListener(TimerEvent.TIMER, removeCow);
deathDelay.start();
//removeChild(cow);
}
}
}
}
public function removeCow(e:TimerEvent):void {
//trace("removeCow");
removeChild(cow);
deathDelay.stop();
deathDelay.removeEventListener(TimerEvent.TIMER, removeCow);
}
}
}
It’s the removeChild(cow) line that throws the “null” error. Any help most appreciated.
Cheers,
EN