Flash Error #1009 - actionscript-3

There's a problem with my AS3 code. The Error is:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at mcEnemy/destroyEnemy()[/Users/deorka12/Documents/School/firstGame/mcEnemy.as:94]
at firstGame/checkEnemiesOffscreen()[/Users/deorka12/Documents/School/firstGame/firstGame.as:112]
at firstGame/gameLoop()[/Users/deorka12/Documents/School/firstGame/firstGame.as:63]
And this is how my code is:
package {
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
// public function kan je ook gebruiken in een ander as. file
// private function kan je alleen gebruiken in hetzelfde as. file
public class firstGame extends MovieClip
{
public var mcPlayer:MovieClip;
private var leftKeyIsDown:Boolean;
private var rightKeyIsDown: Boolean;
private var aMissileArray: Array;
private var aEnemyArray: Array;
public function firstGame (){
//initilaiz variables
aMissileArray = new Array ();
aEnemyArray = new Array ();
//trace("First Game Loaded");
//Listern for key presses and relesead
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
//Setup game event loop
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
// create a timer object
var tEnemyTimer : Timer = new Timer (1000);
// listener for timer intervals
tEnemyTimer.addEventListener(TimerEvent.TIMER, addEnemy);
// start out timer
tEnemyTimer.start();
}
private function addEnemy (e:TimerEvent) : void
{
//trace ("timer ticks")
// create a new enemy object
var newEnemy:mcEnemy = new mcEnemy ();
// add object to the stage
stage.addChild (newEnemy);
// add enemy to new enemy to a new enemy array
aEnemyArray.push(newEnemy);
trace (aEnemyArray.length);
}
private function gameLoop (e:Event) : void
{
playerControl();
clampPlayerToStage();
checkMissileOffscreen();
**checkEnemiesOffscreen();**
checkMissilesHitsEnemy();
}
private function checkMissilesHitsEnemy (): void
{
// loop trough current missiles
for (var i : int = 0 ; i < aMissileArray.length; i++)
{
// get our current missile in the i loop
var currentMissile : mcMissile = aMissileArray [i];
// loop trough all our enemies
// gebruik geen i want die is al gebruikt dus j
for (var j: int = 0 ; j < aEnemyArray.length; j++)
{
// get the current enemy in the j loop
var currentEnemy: mcEnemy = aEnemyArray [j];
// test if our current enemy is hitting our current missile
if(currentMissile.hitTestObject(currentEnemy))
{
// remove the missile
currentMissile.destroyMissile();
// remove the missile from missile array
aMissileArray.splice(i, 1);
// remove the enemy from the stage
**currentEnemy.destroyEnemy();**
// remove the enemy from the enemy array
aEnemyArray.splice(j, 1);
}
}
}
}
private function checkEnemiesOffscreen (): void
{
// loop trough all our enemies
for (var i:int = 0;i < aEnemyArray.length; i++)
{
// get our current ememy in the loop
var currentEnemy: mcEnemy = aEnemyArray [i];
// when enemy moves left and is has gone past the and of the left from the stage
if (currentEnemy.sDirection == "L" && currentEnemy.x - (currentEnemy.width/2))
{
// Remove enemy from our array
aEnemyArray.slice(i,1);
// Remove enemy from stage
currentEnemy.destroyEnemy();
} else
if (currentEnemy.sDirection == "R" && currentEnemy.x > stage.stageWidth + (currentEnemy.width/2))
{
// Remove enemy from our array
aEnemyArray.slice(i,1);
// Remove enemy from stage
currentEnemy.destroyEnemy();
}
}
}
private function checkMissileOffscreen():void
{
//Loop throw all our missiles in our missle array
// i = counter object
for (var i: int = 0; i < aMissileArray.length; i++)
{
//Get the current missile in the loop
var currentMissile : mcMissile = aMissileArray [i];
//Test if current missile is out the buttom of the screen
if (currentMissile.y > 450 )
{
//Remove current missile from the array
aMissileArray.splice(i,1);
//Destroy our missile
currentMissile.destroyMissile();
}
}
}
private function clampPlayerToStage ():void
{
// if our player is to the left of the stage
if (mcPlayer.x < (mcPlayer.width/2))
{
// set our player to left of the stage
mcPlayer.x = mcPlayer.width/2;
}
// if our player is to the right of the stage
else if (mcPlayer.x > (stage.stageWidth - (mcPlayer.width/2)))
{
//set our player to right of the stage
mcPlayer.x = stage.stageWidth - (mcPlayer.width/2);
}
}
private function playerControl ():void
{
// if our left key is down currently
if (leftKeyIsDown == true)
{
//move to left
mcPlayer.x -= 5;
}
// if our right key is currently down
if (rightKeyIsDown)
{
//move to right
mcPlayer.x += 5;
}
}
private function keyUp (e:KeyboardEvent): void
{
//trace(e.keyCode)
//if your left is released
if (e.keyCode == 37)
{
//left key is released
leftKeyIsDown = false;
}
//if your right is released
if (e.keyCode == 39)
{
//right key is released
rightKeyIsDown = false;
}
//if our spacebarr is released
if (e.keyCode == 32)
{
//fire a missile
fireMissile ();
}
}
private function fireMissile ():void
{
// create a new missisile object
var newMissile : mcMissile = new mcMissile ();
// add to stage
stage.addChild(newMissile);
// position missile
newMissile.x = mcPlayer.x;
newMissile.y = mcPlayer.y;
//add our new missile to our missile array
aMissileArray.push (newMissile);
trace(aMissileArray.length)
}
private function keyDown (e:KeyboardEvent): void
{
//trace(e.keyCode)
//if your left is pressed
if (e.keyCode == 37)
{
//left key is pressed
leftKeyIsDown = true;
}
//if your right is pressed
if (e.keyCode == 39)
{
//right key is pressed
rightKeyIsDown = true;
}
}
}
}
and my other code is:
package {
import flash.display.MovieClip;
import flash.events.Event;
public class mcEnemy extends MovieClip {
public var sDirection:String;
private var nSpeed:Number;
public function mcEnemy()
{
addEventListener(Event.ADDED_TO_STAGE, onAdd);
}
private function onAdd (e:Event): void
{
removeEventListener(Event.ADDED_TO_STAGE, onAdd);
init();
}
private function init ():void
{
// 3 frames
var nEnemies:Number = 3;
// pick random number between 1 and number of enemies
var nRandom:Number = randomNumber (1, nEnemies);
// Setup our playhead of this enemy clip to a random number
// Stop op frame 1,2 of 3
this.gotoAndStop(nRandom);
// Setup our enemys start position
setupStartPosition();
}
private function setupStartPosition (): void
{
// pick a random speed for the enemy
nSpeed = randomNumber (5,10);
// Pick random number for left or right, start position
var nLeftOrRight:Number = randomNumber (1,2);
// if our nLeftOrRight == 1 , enemy is on the left
if (nLeftOrRight == 1)
{
// start enemy on the left side
this.x = - (this.width/2);
sDirection = "R";
} else
{
// start enemy on the right side
this.x = stage.stageWidth + (this.width/2);
sDirection = "L";
}
// set a random hoogte for our enemy
// set a 2 varibele for min and max hoogte
var nMinAltitude: Number = stage.stageHeight/2;
var nMaxAltitude: Number = 400 - (this.height/2);
// Setup our enemies altitude to a random point between our min and max altitudes
this.y = randomNumber (nMinAltitude, nMaxAltitude);
// move our enemy
startMoving ();
}
private function startMoving (): void
{
addEventListener(Event.ENTER_FRAME, enemyLoop)
}
private function enemyLoop (e:Event ): void
{
// test in what direction our enemy is moving
// if our enemy is moving right
if (sDirection == "R")
{
// move our enemy right
this.x += nSpeed;
} else
{
this.x -= nSpeed;
}
}
// geeft random nummer tussen 0 en 1
function randomNumber (low:Number=0, high:Number=1) : Number
{
return Math.floor (Math.random() * (1+high-low)) + low;
}
public function destroyEnemy (): void
{
// remove enemys from the stage
**parent.removeChild(this);**
// remove any eventlisteners from enemy
removeEventListener(Event.ENTER_FRAME, enemyLoop);
}
}
}
I hope someone can help me. Sorry for my bad english.

The error indicates that the property parent is null, meaning that your mcEnemy object has no parent. The mcEnemy object has not been added to the display list.
To fix this you can check the parent property is set first:
if(parent)
{
parent.removeChild(this);
}

Related

5006: An ActionScript file can not have more than one externally visible definition: AND TypeError: Error #1006: hitTestObject is not a function

I have 2 issues in this code.
The first is:
5006: An ActionScript file can not have more than one externally visible definition: Sprayer, bugs
I've put multiple Actionscripts together to create this, i've seperated out the classes and am hoping to play this on a frame from a symbol.
and the second relates to:
Error #1006: hitTestObject is not a function
For this i'm trying to get the aagun/Sprayer to lose health then lives if the bugs touch it, but i'm not sure why it's saying it's not a function. Am I using the wrong words?
Thanks for your help, here's the code
package Shooter{
import flash.display.*;
import flash.events.*;
import flash.utils.getTimer;
class Sprayer extends MovieClip{
const speed:Number = 150.0;
var lastTime:int; // animation time
function Sprayer() {
// initial location of gun
this.x = 275;
this.y = 340;
// movement
addEventListener(Event.ENTER_FRAME,moveGun);
}
function moveGun(event:Event) {
// get time difference
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// current position
var newx = this.x;
// move to the left
if (MovieClip(parent).leftArrow) {
newx -= speed*timePassed/1000;
}
// move to the right
if (MovieClip(parent).rightArrow) {
newx += speed*timePassed/1000;
}
// check boundaries
if (newx < 10) newx = 10;
if (newx > 540) newx = 540;
// reposition
this.x = newx;
}
// remove from screen and remove events
function deleteGun() {
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveGun);
}
}
}
package BigBug{
import flash.display.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.TextField;
import flash.display.MovieClip;
class bugs extends MovieClip {
var dx:Number; // speed and direction
var lastTime:int; // animation time
function bugs(side:String, speed:Number, altitude:Number) {
if (side == "left") {
this.x = -50; // start to the left
dx = speed; // fly left to right
this.scaleX = 1; // reverse
} else if (side == "right") {
this.x = -50; // start to the right
dx = -speed; // fly right to left
this.scaleX = 1; // not reverse
}
this.y = altitude; // vertical position
// choose a random plane
this.gotoAndStop(Math.floor(Math.random()*4+1));
// set up animation
addEventListener(Event.ENTER_FRAME,movePlane);
lastTime = getTimer();
}
function movePlane(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move plane
this.x += dx*timePassed/2000;
// check to see if off screen
if ((dx < 0) && (x < -50)) {
deletePlane();
} else if ((dx > 0) && (x > 350)) {
deletePlane();
}
}
}
}
package Missiles{
import flash.display.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.TextField;
import flash.display.MovieClip;
class Bullets extends MovieClip {
var dx:Number; // vertical speed
var lastTime:int;
function Bullets(x,y:Number, speed: Number) {
// set start position
this.x = x;
this.y = y;
// get speed
dx = speed;
// set up animation
lastTime = getTimer();
addEventListener(Event.ENTER_FRAME,moveBullet);
}
function moveBullet(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move bullet
this.x += dx*timePassed/1000;
// bullet past top of screen
if (this.x < 0) {
deleteBullet();
}
}
// delete bullet from stage and plane list
function deleteBullet() {
MovieClip(parent).removeBullet(this);
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveBullet);
}
}
}
package MainGame{
import flash.display.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.TextField;
import flash.display.MovieClip;
import Missiles.Bullets;
import Shooter.Sprayer;
import BigBug.bugs;
public class AirRaid extends MovieClip {
private var aagun:Sprayer;
private var airplanes:Array;
private var buggood:Array;
private var bullets:Array;
public var leftArrow, rightArrow:Boolean;
private var nextGbug:Timer;
private var nextPlane:Timer;
private var shotsLeft:int;
private var shotsHit:int;
public function startAirRaid() {
// init score
shotsLeft = 20;
shotsHit = 0;
showGameScore();
// create gun
aagun = new Sprayer();
addChild(aagun);
// create object arrays
buggood = new Array();
airplanes = new Array();
bullets = new Array();
// listen for keyboard
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
// look for collisions
addEventListener(Event.ENTER_FRAME,checkForHits);
// start planes flying
setNextPlane();
setNextGbug();
}
public function setNextPlane() {
nextPlane = new Timer(1000+Math.random()*1000,1);
nextPlane.addEventListener(TimerEvent.TIMER_COMPLETE,newPlane);
nextPlane.start();
}
public function newPlane(event:TimerEvent) {
// random side, speed and altitude
if (Math.random() > .5) {
var side:String = "left";
} else {
side = "right";
}
var altitude:Number = Math.random()*50+20;
var speed:Number = Math.random()*150+150;
// create plane
var p:bugs = new bugs(side,speed,altitude);
addChild(p);
airplanes.push(p);
// set time for next plane
setNextPlane();
}
public function setNextGbug() {
nextGbug = new Timer(1000+Math.random()*1000,1);
nextGbug.addEventListener(TimerEvent.TIMER_COMPLETE,newGbug);
nextGbug.start();
}
public function newGbug(event:TimerEvent) {
// random side, speed and altitude
if (Math.random() > .5) {
var side:String = "left";
} else {
side = "right";
}
var altitude:Number = Math.random()*50+20;
var speed:Number = Math.random()*150+150;
// create Gbug
var p:Good_bug = new Good_bug(side,speed,altitude);
addChild(p);
buggood.push(p);
// set time for next Gbug
setNextGbug();
}
// check for collisions
public function checkForHits(event:Event) {
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var airplaneNum:int=airplanes.length-1;airplaneNum>=0;airplaneNum--) {
if (bullets[bulletNum].hitTestObject(airplanes[airplaneNum])) {
airplanes[airplaneNum].planeHit();
bullets[bulletNum].deleteBullet();
shotsHit++;
showGameScore();
break;
}
}
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var Good_bugNum:int=buggood.length-1;Good_bugNum>=0;Good_bugNum--) {
if (bullets[bulletNum].hitTestObject(buggood[Good_bugNum])) {
buggood[Good_bugNum].GbugHit();
bullets[bulletNum].deleteBullet();
shotsHit--;
showGameScore();
break;
}
}
}
if ((shotsLeft == 0) && (bullets.length == 0)) {
endGame();
}
}
if ((shotsLeft == 0) && (bullets.length == 0)) {
endGame();
}
}
// key pressed
public function keyDownFunction(event:KeyboardEvent) {
if (event.keyCode == 37) {
leftArrow = true;
} else if (event.keyCode == 39) {
rightArrow = true;
} else if (event.keyCode == 32) {
fireBullet();
}
}
// key lifted
public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 37) {
leftArrow = false;
} else if (event.keyCode == 39) {
rightArrow = false;
}
}
// new bullet created
public function fireBullet() {
if (shotsLeft <= 0) return;
var b:Bullets = new Bullets(aagun.x,aagun.y,-300);
addChild(b);
bullets.push(b);
shotsLeft--;
showGameScore();
}
public function showGameScore() {
showScore.text = String("Score: "+shotsHit);
showShots.text = String("Shots Left: "+shotsLeft);
}
// take a plane from the array
public function removePlane(plane:bugs) {
for(var i in airplanes) {
if (airplanes[i] == plane) {
airplanes.splice(i,1);
break;
}
}
}
// take a Gbug from the array
public function removeGbug(Gbug:Good_bug) {
for(var i in buggood) {
if (buggood[i] == Gbug) {
buggood.splice(i,1);
break;
}
}
}
// take a bullet from the array
public function removeBullet(bullet:Bullets) {
for(var i in bullets) {
if (bullets[i] == bullet) {
bullets.splice(i,1);
break;
}
}
}
// game is over, clear movie clips
public function endGame() {
// remove planes
for(var i:int=airplanes.length-1;i>=0;i--) {
airplanes[i].deletePlane();
}
for(var i:int=buggood.length-1;i>=0;i--) {
buggood[i].deleteGbug();
}
airplanes = null;
buggood = null;
aagun.deleteGun();
aagun = null;
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
removeEventListener(Event.ENTER_FRAME,checkForHits);
nextPlane.stop();
nextPlane = null;
nextGbug.stop();
nextGbug = null;
gotoAndStop("gameover");
}
}
}
1.
5006: An ActionScript file can not have more than one externally visible definition: Sprayer, bugs
As it says exactly: you can't have more than one public definition in a file. You have to either split the code to several files or move definitions, that you don't need public, out of the package.
This would be Ok in one file:
package
{
import flash.display.MovieClip;
// public is the default access modifier
public class Test1 extends MovieClip
{
public function Test1()
{
trace("test1");
var t2:Test2 = new Test2();
var t3:Test3 = new Test3();
}
}
}
// Test2 and Test3 are defined outside of the package, otherwise it wouldn't compile.
// These definitions will only be visible to code in this file.
import flash.display.MovieClip;
class Test2 extends MovieClip
{
public function Test2()
{
trace("test2");
}
}
class Test3 extends MovieClip
{
public function Test3()
{
trace("test3");
}
}
2.
Error #1006: hitTestObject is not a function
This usually means that hitTestObject() is not defined on the object (or it's ancestors) you are trying to call it from (although there could be different kinds of errors for that).
hitTestObject() is accessed in two ways in your code: airplanes.hitTestObject() and bullets[bulletNum].hitTestObject(). You will have to debug your code to see what is actually airplanes and bullets[bulletNum], what types they are and whether they inherit hitTestObject() method. You could at least trace() them.

AS3 vertical shooter: Mouse click not working

I'm just trying to make a simple vertical shooter, one where the player's ship is controlled by the mouse and fires a laser when you click the mouse. However, when I try running the code, I keep getting the same error message:
"1046: Type was not found or was not a compile-time constant: MouseEvent."
The thing is, I declared the MouseEvent. I know I did. It is as follows:
--==--
package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
public class SpaceShooter_II extends MovieClip //The public class extends the class to a movie clip.
{
public var army:Array; //the Enemies will be part of this array.
///*
//Laser Shots and Mouse clicks:
import flash.events.MouseEvent;
public var playerShot:Array; //the player's laser shots will fill this array.
public var mouseClick:Boolean;
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseGoDown);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseGoUp);
stage.addEventListener(Event.ENTER_FRAME, onTick);
//*/
//Back to the rest of the code:
public var playerShip:PlayerShip; //This establishes a variable connected to the PlayerShip AS.
public var onScreen:GameScreen; //This establishes a variable that's connected to the GameScreen AS.
public var gameTimer:Timer; //This establishes a new variable known as gameTimer, connected to the timer utility.
///*
//Functions connected to Shooting via mouse-clicks:
public function mouseGoDown(event:MouseEvent):void
{
mouseClick = true;
}
public function mouseGoUp(event:MouseEvent):void
{
mouseClick = false;
}
//*/
//This function contains the bulk of the game's components.
public function SpaceShooter_II()
{
//This initiates the GameScreen.
onScreen = new GameScreen;
addChild ( onScreen );
//This sets up the enemy army.
army = new Array(); //sets the "army" as a NEW instance of array.
var newEnemy = new Enemy( 100, -15); //This will create new enemies. There's new var newEnemy statement, hence we call THIS a var.
army.push ( newEnemy ); //the new enemy is added to the army.
addChild( newEnemy ); //the new enemy is added to the game.
//This sets up the player's avatar, a spaceship.
playerShip = new PlayerShip(); //This invokes a new instance of the PlayerShip...
addChild( playerShip ); //...And this adds it to the game.
playerShip.x = mouseX; //These two variables place the "playerShip" on-screen...
playerShip.y = mouseY; //...at the position of the mouse.
///*
//This sets up the player's laser shots:
playerShot = new Array(); //sets the "army" as a NEW instance of array.
var goodShot = new goodLaser( playerShip.x, playerShip.y); //This will create new enemies. There's new var newEnemy statement, hence we call THIS a var.
playerShot.push ( goodShot ); //the new enemy is added to the army.
addChild( goodShot ); //the new enemy is added to the game.
//*/
//This sets up the gameTimer, where a lot of the action takes place.
gameTimer = new Timer( 25 );
gameTimer.addEventListener( TimerEvent.TIMER, onTick );
gameTimer.start();
}
//This function contains the things that happen during the game (player movement, enemy swarms, etc.)
public function onTick( timerEvent:TimerEvent ):void
{
//This "if" statement is where the array that contains the enemy ships is initialized.
if ( Math.random() < 0.05 ) //This sets the number of ships showing up at once.
{
var randomX:Number = Math.random() * 800 //Generates a random number between 0 and 1.
var newEnemy:Enemy = new Enemy ( randomX, -15 ); //This shows where the enemy starts out--at a random position on the X plane, but at a certain points on the Y plane.
army.push( newEnemy ); //This adds the new enemy to the "army" Array.
addChild( newEnemy ); //This makes the new enemy part of the game.
}
//This "for" statement sends the enemies downward on the screen.
for each (var enemy:Enemy in army) //Every time an enemy is added to the "army" array, it's sent downward.
{
enemy.moveDown(); //This is the part that sends the enemy downward.
//And now for the collision part--the part that establishes what happens if the enemy hits the player's spaceship:
if ( playerShip.hitTestObject ( enemy ) ) //If the playerShip makes contact with the enemy...
{
gameTimer.stop(); //This stops the game.
dispatchEvent( new PlayerEvent(PlayerEvent.BOOM) ); //This triggers the game over screen in the PlayerEvent AS
}
}
//This, incidentally, is the player's movement controls:
playerShip.x = mouseX;
playerShip.y = mouseY;
///*
//And this SHOULD be the shooting controls, if the mouse function would WORK...
if ( mouseClick = true )
{
var goodShot = new goodLaser( playerShip.x, playerShip.y); //This will create new lasers. There's new variable in the statement, hence we call THIS a variable.
playerShot.push ( goodShot ); //the new laser is added to the army.
addChild( goodShot ); //the new laser is added to the game.
}
for each (var goodlaser: goodLaser in goodShot)
{
goodlaser.beamGood();
}
//*/
}
}
}
--==--
Sorry if the brackets are coming in uneven, I just wanted to outline the code in its entirety, and show the parts I added where things started going wrong, so someone can tell me what I need to do to make this work.
Basically, everything else works...but when I work on the things connected to the mouse clicking and the array with the lasers, the program stops working. The error seems to be connected to the functions "mouseGoUp" and "mouseGoDown," but I'm not sure how to fix that.
This assignment is due March 8. Can someone help me, please?
Add this import flash.events.MouseEvent; to the top of your class and it should work. You need to import everything you use. That's why you get that error.
As well as importing MouseEvent, in the initialisation of your game, you should add event listeners to the stage which listen for the MOUSE_DOWN and MOUSE_UP events:
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseGoDown);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseGoUp);
What would be simpler, though, would be to do away with the 'mouseClick' variable and have just a single MouseEvent listener which listens for the MOUSE_DOWN event and trigger your missle launch from the handler.
I had a game like this if you want the entire source i can give it to you but the main parts are
var delayCounter:int = 0;
var mousePressed:Boolean = false;
var delayMax:int = 5;//How rapid the fire is
var playerSpeed:int = 5;
var bulletList:Array = [];
var bullet:Bullet;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
stage.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler,false,0,true);
stage.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler,false,0,true);
stage.addEventListener(Event.ENTER_FRAME,loop,false,0,true);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function loop(e:Event):void
{
player.rotation = Math.atan2(mouseY - player.y,mouseX - player.x) * 180 / Math.PI + 90;
if (bulletList.length > 0)
{
for each (bullet in bulletList)
{
bullet.bulletLoop();
}
}
if (mousePressed)
{
delayCounter++;
if ((delayCounter == delayMax))
{
shootBullet();
delayCounter = 0;
}
}
if (upPressed)
{
player.y -= playerSpeed;
}
if (downPressed)
{
player.y += playerSpeed;
}
if (leftPressed)
{
player.x -= playerSpeed;
}
if (rightPressed)
{
player.x += playerSpeed;
}
}
function mouseDownHandler(e:MouseEvent):void
{
mousePressed = true;
}
function mouseUpHandler(e:MouseEvent):void
{
mousePressed = false;
}
function shootBullet():void
{
var bullet:Bullet = new Bullet(stage,player.x,player.y,player.rotation - 90);
bulletList.push(bullet);
stage.addChildAt(bullet,1);
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
if (event.keyCode == 87)
{
upPressed = true;
}
if (event.keyCode == 83)
{
downPressed = true;
}
if (event.keyCode == 65)
{
leftPressed = true;
}
if (event.keyCode == 68)
{
rightPressed = true;
}
}
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
if (event.keyCode == 87)
{
upPressed = false;
}
if (event.keyCode == 83)
{
downPressed = false;
}
if (event.keyCode == 65)
{
leftPressed = false;
}
if (event.keyCode == 68)
{
rightPressed = false;
}
}
BULLET CLASS
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
public class Bullet extends MovieClip
{
private var stageRef:Stage;
private var speed:Number = 10;//speed that the bullet will travel at
private var xVel:Number = 5;
private var yVel:Number = 5;
private var rotationInRadians = 0;
public function Bullet(stageRef:Stage, X:int, Y:int, rotationInDegrees:Number):void
{
this.stageRef = stageRef;
this.x = X;
this.y = Y;
this.rotation = rotationInDegrees;
this.rotationInRadians = rotationInDegrees * Math.PI / 180;
}
public function bulletLoop():void
{
xVel = Math.cos(rotationInRadians) * speed;
yVel = Math.sin(rotationInRadians) * speed;
x += xVel;
y += yVel;
if (x > stageRef.stageWidth || x < 0 || y > stageRef.stageHeight || y < 0)
{
deleteBullet();
}
}
public function deleteBullet()
{
this.visible=false
this.x=9999
this.y=9999
}
}
}

error 1118: Implicit coercion of a value with static type flash.display:DisplayObject to a possibly unrelated type flash.display:MovieClip

Building a top down shooter, and after fixing some bugs an making everything work i am left with only one more.
error 1118: Implicit coercion of a value with static type flash.display:DisplayObject to a possibly unrelated type flash.display:MovieClip.
This is the Level.as where all the object are loaded
package {
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.filters.BlurFilter;
import flash.utils.Timer;
import flash.text.TextField;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.utils.*;
import flash.display.Shape;
import flash.display.DisplayObject
/**
*
*/
public class Level extends Sprite
{
//these booleans will check which keys are down
public var leftIsPressed:Boolean = false;
public var rightIsPressed:Boolean = false;
public var upIsPressed:Boolean = false;
public var downIsPressed:Boolean = false;
//how fast the character will be able to go
public var speed:Number = 5;
public var vx:Number = 0;
public var vy:Number = 0;
//how much time before allowed to shoot again
public var cTime:int = 0;
//the time it has to reach in order to be allowed to shoot (in frames)
public var cLimit:int = 12;
//whether or not the user is allowed to shoot
public var shootAllow:Boolean = true;
//how much time before another enemy is made
public var enemyTime:int = 0;
//how much time needed to make an enemy
//it should be more than the shooting rate
//or else killing all of the enemies would
//be impossible :O
public var enemyLimit:int = 16;
//the spaceAuto's score
public var score:int = 0;
//this movieclip will hold all of the bullets
public var bulletContainer:MovieClip = new MovieClip();
//whether or not the game is over
public var gameOver:Boolean = false;
public var SpaceAuto:spaceAuto = new spaceAuto;
// publiek toegangkelijke verwijzing naar deze class
public static var instance:Level;
public var particleContainer:MovieClip = new MovieClip();
// constructor code
public function Level()
{
instance = this;
SpaceAuto.x = 135;
SpaceAuto.y = 350;
addChild(this.SpaceAuto);
addChild(this.bulletContainer);
Project.instance.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
Project.instance.stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
Project.instance.stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
Project.instance.stage.addEventListener(Event.ENTER_FRAME, generateParticles);
//checking if there already is another particlecontainer there
if(!contains(particleContainer))
{
//this movieclip will hold all of the particles
addChild(this.particleContainer);
}
}
function keyDownHandler(e:KeyboardEvent):void {
switch(e.keyCode) {
case Keyboard.LEFT : leftIsPressed = true; break;
case Keyboard.RIGHT : rightIsPressed = true; break;
case Keyboard.UP : upIsPressed = true; break;
case Keyboard.DOWN : downIsPressed = true; break;
}
if(e.keyCode == 32 && shootAllow)
{
//making it so the user can't shoot for a bit
shootAllow = false;
//declaring a variable to be a new Bullet
var newBullet:Bullet = new Bullet();
//changing the bullet's coordinates
newBullet.x = SpaceAuto.x + SpaceAuto.width/2 - newBullet.width/2;
newBullet.y = SpaceAuto.y;
//then we add the bullet to stage
bulletContainer.addChild(newBullet);
}
}
function keyUpHandler(e:KeyboardEvent):void {
switch(e.keyCode) {
case Keyboard.LEFT : leftIsPressed = false; break;
case Keyboard.RIGHT : rightIsPressed = false; break;
case Keyboard.UP : upIsPressed = false; break;
case Keyboard.DOWN : downIsPressed = false; break;
}
}
function enterFrameHandler(e:Event):void {
vx = -int(leftIsPressed)*speed + int(rightIsPressed)*speed;
vy = -int(upIsPressed)*speed + int(downIsPressed)*speed;
SpaceAuto.x += vx;
SpaceAuto.y += vy;
if(cTime < cLimit)
{
cTime ++;
trace("++")
}
else
{
//if it has, then allow the user to shoot
shootAllow = true;
//and reset cTime
cTime = 0;
}
//adding enemies to stage
if(enemyTime < enemyLimit)
{
//if time hasn't reached the limit, then just increment
enemyTime ++;
}
else
{
//defining a variable which will hold the new enemy
var newEnemy = new Enemy();
//making the enemy offstage when it is created
newEnemy.y = -1 * newEnemy.height;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
newEnemy.x = int(Math.random()*(stage.stageWidth - newEnemy.width));
//then add the enemy to stage
addChild(newEnemy);
//and reset the enemyTime
enemyTime = 0;
}
//updating the score text
txtScore.text = 'Score: '+score;
if (gameOver == true)
{
loadScreenThree();
}
}
function generateParticles(event:Event):void
{
//so we don't do it every frame, we'll do it randomly
if(Math.random()*10 < 2){
//creating a new shape
var mcParticle:Shape = new Shape();
//making random dimensions (only ranges from 1-5 px)
var dimensions:int = int(Math.random()*5)+1;
//add color to the shape
mcParticle.graphics.beginFill(0x999999/*The color for shape*/,1/*The alpha for the shape*/);
//turning the shape into a square
mcParticle.graphics.drawRect(dimensions,dimensions,dimensions,dimensions);
//change the coordinates of the particle
mcParticle.x = int(Math.random()*stage.stageWidth);
mcParticle.y = -10;
//adding the particle to stage
particleContainer.addChild(mcParticle);
}
//making all of the particles move down stage
for(var i:int=particleContainer.numChildren - 1; i>=0; i--){
//getting a certain particle
var theParticle:DisplayObject = particleContainer.getChildAt(i);
//it'll go half the speed of the character
theParticle.y += speed*.5;
//checking if the particle is offstage
if(theParticle.y >= 400){
//remove it
particleContainer.removeChild(theParticle);
}
}
}
/**
* eventhandler voor als je op de tweede knop klikt
*/
private function loadScreenThree():void
{
// eerst opruimen!
cleanListeners();
// dan naar ander scherm
Project.instance.switchScreen( "derde" );
}
private function cleanListeners():void
{
stage.removeEventListener(Event.ENTER_FRAME, generateParticles);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
}}
Where it goes wrong is in the Enemy Class in the eFrame Function. Here a loop runs trough the array bulletContainer from Level.as. A new variable is made and it should consist of the bullet that is in the loop out of the bulletContainer, and here comes the error in place
package{
//we have to import certain display objects and events
import Level;
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Sprite;
//this just means that Enemy will act like a MovieClip
public class Enemy extends MovieClip
{
//VARIABLES
//this will act as the root of the document
//so we can easily reference it within the class
private var _root:Object;
//how quickly the enemy will move
private var speed:int = 5;
//this function will run every time the Bullet is added
//to the stage
public function Enemy()
{
//adding events to this class
//functions that will run only when the MC is added
addEventListener(Event.ADDED, beginClass);
//functions that will run on enter frame
addEventListener(Event.ENTER_FRAME, eFrame);
}
private function beginClass(event:Event):void
{
_root = Sprite(root);
}
private function eFrame(event:Event):void
{
//moving the bullet up screen
y += speed;
//making the bullet be removed if it goes off stage
if(this.y > 400)
{
removeEventListener(Event.ENTER_FRAME, eFrame);
this.parent.removeChild(this);
}
//checking if it is touching any bullets
//we will have to run a for loop because there will be multiple bullets
for(var i:int = 0;i<Level.instance.bulletContainer.numChildren;i++)
{
//numChildren is just the amount of movieclips within
//the bulletContainer.
trace("LOOOOOOOOOP");
trace(Level.instance.bulletContainer.getChildAt(i));
//we define a variable that will be the bullet that we are currently
//hit testing.
var bulletTarget:Sprite = Level.instance.bulletContainer.getChildAt(i);
//now we hit test
if(hitTestObject(bulletTarget))
{
//remove this from the stage if it touches a bullet
removeEventListener(Event.ENTER_FRAME, eFrame);
this.parent.removeChild(this);
//also remove the bullet and its listeners
Level.instance.bulletContainer.removeChild(bulletTarget);
//bulletTarget.removeListeners();
//up the score
Level.instance.score += 5;
}
}
//hit testing with the user
if(hitTestObject(Level.instance.SpaceAuto))
{
//losing the game
trace("DOOOOOD");
removeListeners();
this.parent.removeChild(this);
this.removeEventListener(Event.ENTER_FRAME, eFrame);
Level.instance.gameOver = true;
}
}
public function removeListeners():void
{
this.removeEventListener(Event.ENTER_FRAME, eFrame);
}
}}
i have tried make it Sprite or anything else but i just dont know how to fix this so it wil take the bullet so i van see if it hits the Enemy
var bulletTarget:Sprite = Level.instance.bulletContainer.getChildAt(i);
getChildAt will return a DisplayObject type, and hitTestObject requires a parameter with DisplayObject type.
So try this in your Enemy's eFrame function.
var bulletTarget:DisplayObject = Level.instance.bulletContainer.getChildAt(i);

Error: #1009: Type Error (Line #114)

I'm sort of a noob to flash, but I am programming a game right now, and I am trying to make my character move but i am getting error #1009 Here is my code in my "GameState".
Basically it errors out on any Keypress, I have my character named player (Player in the library) and it has another movie clip within it named WalkDown (I gave it an instance name of walkDown on the timeline) I am not really sure whats going on. Specifically it errors out on the line where its calling the frame name. Any help would be appreciated!
package {
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.geom.Point;
public class GameState extends MovieClip {
private var player:MovieClip;
private var walking:Boolean = false;
// is the character shooting
//private var shooting:Boolean = false;
// wlaking speed
private var walkingSpeed:Number = 5;
private var xVal:Number = 0;
private var yVal:Number = 0;
public function GameState() {
// constructor code
player = new Player();
addChild(player);
player.x = 300;
player.y = 300;
player.gotoAndStop("stance");
this.addEventListener(Event.ADDED_TO_STAGE, initialise);
}
private function initialise(e:Event){
// add a mouse down listener to the stage
//addEventListener(MouseEvent.MOUSE_DOWN, startFire);
// add a mouse up listener to the stage
//addEventListener(MouseEvent.MOUSE_UP, stopFire);
player.addEventListener(Event.ENTER_FRAME,motion);
stage.addEventListener(KeyboardEvent.KEY_UP,onKey);
// add a keyboard down listener
stage.addEventListener(KeyboardEvent.KEY_DOWN, offKey);
stage.focus = stage;
// Add keyboard events
}
private function motion(e:Event):void{
// if we are currently holding the mouse down
//if (shooting){
//FIRE
//fire();
//}
player.x += xVal;
player.y += yVal;
}
//private function startFire(m:MouseEvent){
//shooting = true;
//}
//private function stopFire(m:MouseEvent){
//shooting = false;
//}
private function onKey(evt:KeyboardEvent):void
{
trace("key code: "+evt.keyCode);
switch (evt.keyCode)
{
case Keyboard.W :
yVal = walkingSpeed;
if (! walking)
{
trace("walking up");
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.S :
yVal = - walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.A :
xVal = walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.D :
xVal = walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
}
}
private function offKey(evt:KeyboardEvent):void
{
switch (evt.keyCode)
{
case Keyboard.W :
//for now just reset velocity to zero
yVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.S :
//for now just reset velocity to zero
yVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.A :
//for now just reset velocity to zero
xVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.D :
//for now just reset velocity to zero
xVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
}
}
// Players Motion
private function fire():void{
var b= new Bullet();
// set the position and rotation of the bullet
b.rotation = rotation;
b.x = x;
b.y = y;
// add bullets to list of bullets
MovieClip(player).bullets.push(b);
// add bullet to parent object
player.addChild(b);
// play firing animation
player.shooting.gotoAndPlay("fire");
}
}
}
You were saying the Error #1009 ( Cannot access a property or method of a null object reference ) arises when you do
player.walkDown.gotoAndPlay("walking");
If so, that is because you have to first go to the frame where the WalkDown MovieClip is in before you can access it.
If say your "stance" frame is in frame 1 and your WalkDown MovieClip is in frame 2. Your code in the onKey function should look like:
case Keyboard.W :
yVal = walkingSpeed;
if (! walking)
{
trace("walking up");
player.gotoAndStop(2); // player.walkDown is now accessible //
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;

game design coding error

/Question/
I have been at this for about a week and still can't find the problem.
I used trace statements but I cant tell whether is this or that. As I am still quite still inexperienced myself. I am using Flash Develop. thanks.
/* This is the error I am getting
I am trying remove the dango once it gets destroyed and remove it again after the game ends */
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at mcDango/destoryDango()[J:\catchMeDango\mcDango.as:72]
at catchMeDango/checkEndGameCondition()[J:\catchMeDango.as:195]
at catchMeDango/gameLoop()[J:\catchMeDango\catchMeDango.as:171]
---------------------------------------------------------------------------------------
/*This is for catchMeDango doc */
package
{
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.TimerEvent;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.utils.Timer;
/**
* ...
* #author
*/
public class catchMeDango extends MovieClip
{
public var skewerPlayer:MovieClip;
private var leftKeyIsDown:Boolean;
private var rightKeyIsDown:Boolean;
private var upKeyIsDown:Boolean;
private var downKeyIsDown:Boolean;
private var aDangoArray:Array;
private var aBlackDangoArray:Array;
public var scoreTxt:TextField;
public var lifeTxt:TextField;
public var menuEnd:mcEndGameScreen;
private var nScore:Number;
private var nLife:Number;
private var tDangoTimer:Timer;
private var tBlackDangoTimer:Timer;
private var menuStart:mcStartGameScreen;
private var startHow:Loader;
public function catchMeDango()
{
//hides the endGameScreen
menuEnd.hideScreen();
//Create loader object
var startLoader:Loader = new Loader();
//Add event listener to listen the complete event
startLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, startLoaded);
//Load our loader object
startLoader.load(new URLRequest("startGameScreen.swf"));
}
private function startHowToPlay(e:Event):void
{
//Create loader object
startHow = new Loader();
//Add event listener to listen the complete event
startHow.contentLoaderInfo.addEventListener(Event.COMPLETE, HowToPlay);
//Load our loader object
startHow.load(new URLRequest("howToPlay.swf"));
}
private function HowToPlay(e:Event):void
{
//add the how to play movie clip to stage
addChild(startHow);
startHow.addEventListener("BEGIN_GAME", playGameAgain);
}
private function startLoaded(e:Event):void
{
//Get a reference to the loaded movieclip
menuStart = e.target.content as mcStartGameScreen;
//Listen for start game event
menuStart.addEventListener("START_GAME", playGameAgain);
menuStart.addEventListener("HOW_TO_PLAY", startHowToPlay);
//Add to stage
addChild(menuStart);
}
private function playGameAgain(e:Event):void
{
//I had to remove this function becuase is was causing errors
//When I click on the "how to play" then go back to the start screen, it hides fine with no issues
//startHow.visible = false;
menuStart.visible = false;
//set keyboard control to false
leftKeyIsDown = false;
rightKeyIsDown = false;
upKeyIsDown = false;
downKeyIsDown = false;
//Initialize variables
aDangoArray = new Array();
aBlackDangoArray = new Array();
nScore = 0;
nLife = 1;
skewerPlayer.visible = true;
menuStart.hideScreen();
menuEnd.addEventListener("PLAY_AGAIN", playGameAgain);
menuEnd.hideScreen();
updateScoreText();
updateLifeText();
//trace ('Catch Me Dango Loaded');
//Set up listerners for when an key is pressed
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
//Set up a game loop listener
stage.addEventListener(Event.ENTER_FRAME, gameLoop)
//Create a timer object for Dango for every 1 second
tDangoTimer = new Timer(1000)
//Listen for timer ticks/intervals
tDangoTimer.addEventListener(TimerEvent.TIMER, addDango)
//Start timer object
tDangoTimer.start();
//Create a timer object for Black Dango for every 10 seconds
tBlackDangoTimer = new Timer(10000)
//Listen for timer ticks/intervals
tBlackDangoTimer.addEventListener(TimerEvent.TIMER, addBlackDango)
//start timer object
tBlackDangoTimer.start();
}
//Display Score Text (Starting form: 0)
private function updateScoreText():void
{
scoreTxt.text = "Score: " + nScore;
}
//Display Life Text (Starting from: 5)
private function updateLifeText():void
{
lifeTxt.text = "Life: " + nLife;
}
private function addBlackDango(e:TimerEvent):void
{
//create new black dango object
var newBlackDango:mcBlackDango = new mcBlackDango();
//Add our new black dango
stage.addChild(newBlackDango);
aBlackDangoArray.push(newBlackDango);
trace(aBlackDangoArray.length);
}
private function addDango(e:TimerEvent):void
{
//create new dango(enemy) object
var newDango:mcDango = new mcDango();
//Create enemy to the stage
stage.addChild(newDango);
//Add our new dango(enemy) to dango(enemy) array collection
aDangoArray.push(newDango);
trace(aDangoArray.length);
}
private function gameLoop(e:Event):void
{
playerContorl();
clampPlayerToStage();
checkDangosOffScreen();
checkSkewerHitsDango();
checkBlackDangosOffScreen();
checkSkwerHitsBlackDango();
checkEndGameCondition();
}
//HELP
private function checkEndGameCondition():void
{
//Check if the player has 0 life left
if (nLife == 0)
{
//Stop player movement
stage.removeEventListener(KeyboardEvent.KEY_UP, keyUp);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDown);
//Hide the player
skewerPlayer.visible = false;
//Stop spawning dango and black dango
tDangoTimer.stop();
tBlackDangoTimer.stop();
//Clear the dango currently on screen
for each(var dango:mcDango in aDangoArray)
{
//this destory function had to be removed as well. because it was destorying the dango twice when it was already removed from the stage.
//by commenting out this, it was able to destory and remove without any errors and only doing it once.
//Destory the dango the were curretly up to in the for loop
dango.destoryDango();
trace("black dango removed")
//Remove from dango from dango array
aDangoArray.splice(0, 1);
}
//Clear the black dango currently on screen
for each(var blackDango:mcBlackDango in aBlackDangoArray)
{
//Destory the dango tat were curretly up to in the for loop
blackDango.destoryBlackDango();
//Remove from dango from dango array
aBlackDangoArray.splice(0, 1);
}
//Stop the game loop
if (aDangoArray.length == 0 && aBlackDangoArray.length == 0)
{
stage.removeEventListener(Event.ENTER_FRAME, gameLoop);
}
//Show end game screen
menuEnd.showScreen();
}
}
// Checks if the Skewer Hits or makes conatct with the Black Dango
private function checkSkwerHitsBlackDango():void
{
//Loop through our current Black dango
for (var i:int = 0; i < aBlackDangoArray.length; i++)
{
//Get our current Black Dango in the loop
var currentBlackDango:mcBlackDango = aBlackDangoArray[i];
//Test if our skewer is hitting the black dango
if (skewerPlayer.hitTestObject(currentBlackDango))
{
//remove the current dango from stage
currentBlackDango.destoryBlackDango()
//Remove the dango from out dango array
aBlackDangoArray.splice(i, 1);
//Minus one to our score
nScore--;
updateScoreText();
//Minus one to our life
nLife--;
updateLifeText();
}
}
}
// Remove the black dango of the stage and from the array
private function checkBlackDangosOffScreen():void
{
//loop through all our black dango
for (var i:int = 0; i < aBlackDangoArray.length; i++)
{
//Get our current dango in the loop
var currentBlackDango:mcBlackDango = aBlackDangoArray[i];
//When dango starts on the top AND our curent enemy has gone past the bottom side if the stage
if (currentBlackDango.y > (stage.stageHeight + currentBlackDango.y / 2))
{
//Remove black dango (enemy) from array
aBlackDangoArray.splice(i, 1);
//Remove black dango (enemy) from stage
currentBlackDango.destoryBlackDango();
}
}
}
// Checks if the Skewer Hits or makes conatct with the Dango
private function checkSkewerHitsDango():void
{
//Loop through all our current dango
for (var i:int = 0; i < aDangoArray.length; i++)
{
//Get our current dango in the loop
var currentDango:mcDango = aDangoArray[i];
//Test if our skewer is hitting dango
if (skewerPlayer.hitTestObject(currentDango))
{
//remove the current dango from stage
currentDango.destoryDango()
//Remove the dango from out dango array
aDangoArray.splice(i, 1);
//Add one to our score
nScore++;
updateScoreText();
}
}
}
// Remove the dango of the stage and from the array
private function checkDangosOffScreen():void
{
//loop through all our dangos(enemies)
for (var i:int = 0; i < aDangoArray.length; i++)
{
//Get our current dango in the loop
var currentDango:mcDango = aDangoArray[i];
//When dango starts on the top AND our curent enemy has gone past the bottom side if the stage
if (currentDango.y > (stage.stageHeight + currentDango.y / 2))
{
//Remove dango (enemy) from array
aDangoArray.splice(i, 1);
//Remove dango (enemy) from stage
currentDango.destoryDango();
}
}
}
private function clampPlayerToStage():void
{
//If our player is to the left of the stage
if (skewerPlayer.x < skewerPlayer.width/2)
{
//Set our player to left of the stage
skewerPlayer.x = skewerPlayer.width/2;
} else if (skewerPlayer.x > (stage.stageWidth - (skewerPlayer.width / 2)))
//If our player is to the right of the stage
{
//Set our player to right of the stage
skewerPlayer.x = stage.stageWidth - (skewerPlayer.width / 2);
}
//If our player is to the top(up) of the stage
if (skewerPlayer.y < 0)
{
//Set our player to the top(up) of the stage
skewerPlayer.y = 0;
} else if (skewerPlayer.y > (stage.stageHeight - (skewerPlayer.height / 1)))
//If our player is to the bottom(down) of the stage
{
//Set our player to the bottom(down) of the stage
skewerPlayer.y = stage.stageHeight - (skewerPlayer.height / 1);
}
}
// right, left, top and bottom Key Functions
private function playerContorl():void
{
//if our left key is currently down
if (leftKeyIsDown == true)
{
//move our player to the left
skewerPlayer.x -= 5;
}
//if our right key is currently down
if (rightKeyIsDown)
{
//move our player to the right
skewerPlayer.x += 5;
}
//if our up key is currently down
if (upKeyIsDown)
{
//move our player to the top
skewerPlayer.y -= 5;
}
//if our down key is currently down
if (downKeyIsDown)
{
//move our player to the bottom
skewerPlayer.y += 5;
}
}
private function keyUp(e:KeyboardEvent):void
{
//if our left key is released
if (e.keyCode == 37)
{
//left key is released
leftKeyIsDown = false;
}
//if our right key is released
if (e.keyCode == 39)
{
//right key is released
rightKeyIsDown = false;
}
//if our up key is released
if (e.keyCode == 38)
{
//up key is released
upKeyIsDown = false;
}
//if our down key is released
if (e.keyCode == 40)
{
//down key is released
downKeyIsDown = false;
}
}
private function keyDown(e:KeyboardEvent):void
{
//if our left key is pressed
if (e.keyCode == 37)
{
//left key is pressed
leftKeyIsDown = true;
}
//if our right key is pressed
if (e.keyCode == 39)
{
//right key is pressed
rightKeyIsDown = true;
}
//if our up key is pressed
if (e.keyCode == 38)
{
//up key is pressed
upKeyIsDown = true;
}
//if our down key is pressed
if (e.keyCode == 40)
{
//right key is pressed
downKeyIsDown = true;
}
}
}
}
---------------------------------------------------------------------------------
/*This is for mcDango doc */
package
{
import flash.display.MovieClip;
import flash.events.Event;
/**
* ...
* #author
*/
public class mcDango extends MovieClip
{
private var nSpeed:Number;
private var nRandom:Number;
public function mcDango()
{
// listen for when the Dango is added to the stage
addEventListener(Event.ADDED_TO_STAGE, onAdd);
}
private function onAdd(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAdd);
init();
}
private function init():void
{ //Number of frames you have in Flash
var nDango:Number = 12;
//Pick random number between 1 and our number of enemies(dango)
var nRandom:Number = randomNumber(1, nDango)
//Setup our player of this enemey(dango) clip to pur random dango
this.gotoAndStop(nRandom);
//Setup our enemies(dango) start position
setupStartPosition();
}
private function setupStartPosition():void
{
//Pick a random speed for enemy(dango)
nSpeed = randomNumber(5, 10);
//Set your ramdon X postion
nRandom = randomNumber(9, 775);
//Start our enemy(dango) on the top side
this.y = -50;
//set random pos X
this.x = nRandom
//move our enmey(dango)
startMoving();
}
private function startMoving():void
{
addEventListener(Event.ENTER_FRAME, dangoLoop)
}
private function dangoLoop(e:Event):void
{
//Test what direction our enemy(dango) is moving in
//If our enemy(dango) is moving right
//Move our enemy(dango) down
this.y += nSpeed
}
public function destoryDango():void
{
//Remove dango from stage
parent.removeChild(this);
trace("the dango has been removed")
//Remove any event listeners in our enemy object
removeEventListener(Event.ENTER_FRAME, dangoLoop);
}
function randomNumber(low:Number=0, high:Number=1):Number
{
return Math.floor(Math.random() * (1+high-low)) + low;
}
}
}
Glancing at the code, looks like the problem is with following for-each-in loop
for each(var dango:mcDango in aDangoArray) {
//this destory function had to be removed as well. because it was destorying the dango twice when it was already removed from the stage.
//by commenting out this, it was able to destory and remove without any errors and only doing it once.
//Destory the dango the were curretly up to in the for loop
dango.destoryDango();
trace("black dango removed")
//Remove from dango from dango array
aDangoArray.splice(0, 1);
}
Check using
while(aDangoArray.length > 0) {
var dango = aDangoArray[0]
dango.destoryDango();
trace("black dango removed")
aDangoArray.splice(0, 1);
}
Well, it looks like the issue is when you try to access the parent.removeChild method. Maybe you already removed it from stage and it doesn't have a parent anymore. Try doing this:
public function destoryDango():void
{
//Remove dango from stage
if(parent != null)
parent.removeChild(this);
trace("the dango has been removed")
//Remove any event listeners in our enemy object
removeEventListener(Event.ENTER_FRAME, dangoLoop);
}