ActionScript 3.0: Error #1034: Type Coercion failed: cannot convert displayObject$ to DefaultPackage at CutomeClass() - actionscript-3

I'm a student I have a final project want to deliver it after two days.
I'm making a drag and drop game, I watched a tutorial to do that.
But after ending coding I faced a weird error!
I've I checked that my code is the same as the code in the tutorial.
This is the Debug error report:
Attempting to launch and connect to Player using URL E:\FL\ActionScript\Drag and Drop Project\DragAndDrop.swf
[SWF] E:\FL\ActionScript\Drag and Drop Project\DragAndDrop.swf - 87403 bytes after decompression
TypeError: Error #1034: Type Coercion failed: cannot convert paper1$ to DragDrop.
at Targets()[E:\FL\ActionScript\Drag and Drop Project\Targets.as:23]
My .fla File is containing 12 Objects to drag and another 12 Objects to drop on it.
The idea here is when drop the Object on the target the Object will become invisible and the target become visible (in .fla file target alpha = 0).
I made two classes:
DragDrop.as : for the objects that I'm going to drag.
Targets.as : for the targets that I'm going to drop Objects on it.
Note: match function is to animate "GameOver" MovieClip When completing the game.
DragDrop.as:
package
{
import flash.display.*;
import flash.events.*;
public class DragDrop extends Sprite
{
var origX:Number;
var origY:Number;
var target:DisplayObject;
public function DragDrop()
{
// constructor code
origX = x;
origY = y;
addEventListener(MouseEvent.MOUSE_DOWN, drag);
buttonMode = true;
}
function drag(evt:MouseEvent):void
{
stage.addEventListener(MouseEvent.MOUSE_UP, drop);
startDrag();
parent.addChild(this);
}
function drop(evt:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, drop);
stopDrag();
if(hitTestObject(target))
{
visible = false;
target.alpha = 1;
Object(parent).match();
}
x = origX;
y = origY;
}
}
}
Targets.as:
package
{
import flash.display.*;
import flash.events.*;
public class Targets extends MovieClip
{
var dragdrops:Array;
var numOfMatches:uint = 0;
var speed:Number = 25;
public function Targets()
{
// constructor code
dragdrops = [paper1,paper2,paper3,paper4,paper5,paper6,
paper7,paper8,paper9,paper10,paper11,paper12,];
var currentObject:DragDrop;
for(var i:uint = 0; i < dragdrops.length; i++)
{
currentObject = dragdrops[i];
currentObject.target = getChildByName(currentObject.name + "_target");
}
}
public function match():void
{
numOfMatches++;
if(numOfMatches == dragdrops.length)
{
win.addEventListener(Event.ENTER_FRAME, winGame);
}
}
function winGame(event:Event):void
{
win.y -= speed;
if(win.y <= 0)
{
win.y = 0;
win.removeEventListener(Event.ENTER_FRAME, winGame);
win.addEventListener(MouseEvent.CLICK, clickWin);
}
}
function clickWin(event:MouseEvent):void
{
win.removeEventListener(MouseEvent.CLICK, clickWin);
win.addEventListener(Event.ENTER_FRAME, animateDown);
var currentObject:DragDrop;
for(var i:uint = 0; i < dragdrops.length; i++)
{
currentObject = dragdrops[i];
getChildByName(currentObject.name + "_target").alpha = 0;
currentObject.visible = true;
}
numOfMatches = 0;
addChild(win);
}
function animateDown(event:Event):void
{
win.y += speed;
if(win.y >= stage.stageHeight)
{
win.y = stage.stageHeight;
win.removeEventListener(Event.ENTER_FRAME, animateDown);
}
}
}
}
...Thanks

Are you sure what you're putting into array in Target instance's array IS DragDrop instances?
dragdrops = [paper1,paper2,paper3,paper4,paper5,paper6,
paper7,paper8,paper9,paper10,paper11,paper12,];
I don't see any definitions for "paper1" in the code. And your error is telling paper1 is not a DragDrop instance.

Related

How can I stop a colliding object from continuing falling after several seconds (AS3)?

I have a problem that is related to AS3, it involves two code locations (MainTimeline and an MC-extending class), as well as a basic physics engine function. The problem is that when the objects collide (enemy and ground), they stay collided, but after a short period of time (2-6 seconds), the object that is gravitated teleports under the object it collided with, and continues to fall.
Thank you for any assistance.
P.S. I do not prefer document class solutions.
Timeline code:
`
stop();
var ground: MovieClip;
var enemy:Enemy = new Enemy();
stage.addChild(enemy);
enemy.x = 400;
enemy.y = 150;
enemy.rotation = 0;
enemy.addEventListener("enterFrame", collisions);
function collisions(e: Event): void {
var collision: Boolean = false;
if (ground.hitTestObject(enemy)) {
collision = true;
}
if (collision) {
while (collision) {
enemy.y -= 0.1;
collision = false;
if (ground.hitTestObject(enemy)) {
collision = true;
}
}
Class(Enemy).yVel = 0;
}
}
Class code:
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Enemy extends MovieClip {
var xVel: int;
var yVel: int;
public function Enemy() {
// constructor code
addEventListener("enterFrame", onEnterFrame);
}
function onEnterFrame(e: Event): void {
yVel += 2;
this.x = xVel;
this.y = yVel;
}
}
}

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.

How can I solve this error in Flash game?

I have a problem in Flash puzzle game. If I create the game in the first frame of my timeline it's working, but if the game has been created (for example) in 5th frame it does'nt work!
It send me this error:
TypeError: Error #1009: Cannot access a property or method of a null
object reference.
at Map() TypeError: Error #2007: Parameter hitTestObject must be non-null.
at flash.display::DisplayObject/_hitTest()
at flash.display::DisplayObject/hitTestObject()
at DragDrop/drop()
dragdrop class
package
{
import flash.display.*;
import flash.events.*;
public class DragDrop extends Sprite
{
var origX:Number;
var origY:Number;
var target:DisplayObject ;
public function DragDrop()
{
// constructor code
origX = x;
origY = y;
addEventListener(MouseEvent.MOUSE_DOWN, drag);
buttonMode = true;
}
function drag(evt:MouseEvent):void
{
stage.addEventListener(MouseEvent.MOUSE_UP, drop);
startDrag();
parent.addChild(this);
}
function drop(evt:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, drop);
stopDrag();
if(hitTestObject(target))
{
visible = false;
target.alpha = 1;
Object(parent).match();
}
x = origX;
y = origY;
}
}
}
I think the problem is in var target! and I don't know how to solve it.
Map.as
enter code here package
{
import flash.display.*;
import flash.events.*;
public class Map extends MovieClip
{
var dragdrops:Array;
public function Map()
{
// constructor code
dragdrops = [tt1];
var currentObject:DragDrop;
for(var i:uint = 0; i < dragdrops.length; i++)
{
currentObject = dragdrops[i];
currentObject.target = getChildByName(currentObject.name + "_target");
}
}
public function match():void
{
}
}
}
Edit:
There are multiple problems with the code. Too many to list, I'm afraid, but the biggest one is:
You're declaring a map, and trying to add your object to it, before your object exists. It doesn't exist until frame 5, so this won't work. I've re-written the code below, but honestly, there is so much wrong with the code that it's just not possible to fix without re-writing significant portions of it.
package
{
import flash.display.*;
import flash.events.*;
public class Map extends MovieClip
{
var dragdrops:Array;
public function Map()
{
// constructor code
dragdrops = new Array();
}
public function addElement(gamepiece:DragDrop):void {
dragdrops.push(gamepiece);
}
public function addChildElements():void {
var currentObject:Object;
for(var i:uint = 0; i < dragdrops.length; i++)
{
currentObject = dragdrops[i];
currentObject.test();
currentObject.target = (currentObject.name + "_target"); // this should work now, but doesn't. Why?
currentObject.target.test();
}
}
public function match():void
{
}
}
}
Then, on frame one, I added:
var map:Map = new Map();
Then, on frame five, I added:
map.addElement(tt1);
map.addChildElements();
This got tt1 added to map, at least, but that's as far as I got. Your problem now is;
currentObject.target = (currentObject.name + "_target");
It's the correct name, now, but it won't add it to target. That's as much as I can do.
It's because your hitTestObject method isn't correctly invoked. This method must be invoked in a Display Object instance to test if another instance of a Display Object hits it:
if (myDisplayObject.hitTestObject(anotherDisplayObject))
{
// do stuff
}
Adobe help about hitTestObject method.
Edit
So you should write you class like that:
package
{
import flash.display.*;
import flash.events.*;
public class DragDrop extends Sprite
{
var origX:Number;
var origY:Number;
var target:DisplayObject;
public function DragDrop()
{
addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event):void {
origX = x;
origY = y;
stage.addEventListener(MouseEvent.MOUSE_DOWN, drag);
buttonMode = true;
}
private function drag(evt:MouseEvent):void
{
stage.addEventListener(MouseEvent.MOUSE_UP, drop);
startDrag();
parent.addChild(this);
}
private function drop(evt:MouseEvent):void
{
target = (evt.target as DisplayObject);
stage.removeEventListener(MouseEvent.MOUSE_UP, drop);
stopDrag();
if(target.hitTestObject(target))
{
visible = false;
target.alpha = 1;
Object(parent).match();
}
x = origX;
y = origY;
}
}
}
Remark
You shouldn't call your variable target, because its the name of a Flash native variable. Rename it targ for example.

Can I get some tips With My Inventory system for my game. I want to use an object in my inventory with another object (like a Key to a Door)

This is my Main Class:
package {
import flash.display.*;
public class InventoryDemo extends MovieClip {
var inventory:Inventory;
public function InventoryDemo() {
}
public function initialiseInventory():void
{
inventory = new Inventory(this);
inventory.makeInventoryItems([d1,d2]);
}
}
}
I used a sprite indicator to show that the items are inside the inventory.
And this is my child class:
package {
import flash.display.*;
import flash.events.*;
public class Inventory
{
var itemsInInventory:Array;
var inventorySprite:Sprite;
public function Inventory(parentMC:MovieClip)
{
itemsInInventory = new Array ;
inventorySprite = new Sprite ;
inventorySprite.x = 50;
inventorySprite.y = 360;
parentMC.addChild(inventorySprite);
}
function makeInventoryItems(arrayOfItems:Array)
{
for (var i:int = 0; i < arrayOfItems.length; i++)
{
arrayOfItems[i].addEventListener(MouseEvent.CLICK,getItem);
arrayOfItems[i].buttonMode = true;
}
}
function getItem(e:Event)
{
var item:MovieClip = MovieClip(e.currentTarget);
itemsInInventory.push(item);
inventorySprite.addChild(item);
item.x = itemsInInventory.length - 1 * 40;
item.y = 0;
item.removeEventListener(MouseEvent.CLICK,getItem);
item.addEventListener(MouseEvent.CLICK,useItem);
}
function useItem(e:Event)
{
var item:MovieClip = MovieClip(e.currentTarget);
trace(("Use Item:" + item.name));
}
}
}
Currently i can only click and trace the output, I was wondering how i can drag the sprite and use it to another object...like a key to unlock a door. Big thanks, btw im new in as3 and im trying to learn from stack overflow.
item.addEventListener(MouseEvent.CLICK,useItem);
var drag:Boolean;
function useItem(e:Event)
{
var item:MovieClip = MovieClip(e.currentTarget);
trace(("Use Item:" + item.name));
if(drag == false)
{
item.startDrag();
drag = true;
}else{
item.stopDrag();
drag = false;
findAction(e);
}
}
function findAction(e)
{
// Check the position of the key relative to the door.
}
Haven't really checked it but it'd probably work if you did something similar.

How to remove all of one class of children from screen in Flash CS4 AS3?

Ok, so I've been stuck on this for about three hours now and I finally feel like asking for help.
Basically, I am trying to remove all instances of an enemy object from the screen when my player ship makes contact with one of them, as he then loses a life and is put back into a safe position on the screen.
EDIT: This is all the code from my Enemy Dude .as file, a bit overboard maybe but nonetheless.
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.media.Sound;
import flash.media.SoundChannel;
public class Enemydude extends MovieClip
{
private var _root:Object;
private var speed:int = 6;
private var shipps = this
public function Enemydude()
{
addEventListener(Event.ADDED, beginclass);
addEventListener(Event.ENTER_FRAME, entFrame);
}
private function beginclass(event:Event):void
{
_root = MovieClip(root);
}
private function entFrame(event:Event):void
{
x -= speed;
if(this.x < -64)
{
removeEventListener(Event.ENTER_FRAME, entFrame);
_root.removeChild(this)
}
if(_root.gameover)
{
x = -700
removeEventListener(Event.ENTER_FRAME, entFrame);
removeEventListener(Event.ADDED, beginclass);
}
for (var i:int = 0; i<_root.playerBulletContainer.numChildren; i++)
{
var bulletTarget:MovieClip = _root.playerBulletContainer.getChildAt(i)
if (hitTestObject(bulletTarget))
{
removeEventListener(Event.ENTER_FRAME, entFrame);
_root.removeChild(this);
_root.playerBulletContainer.removeChild(bulletTarget);
bulletTarget.removeListeners();
_root.Score += 10
makeExplosion();
}
}
if(hitTestObject(_root.mcship))
{
makeExplosion();
shipPos();
removethis();
}
}
private function makeExplosion()
{
var sndExplode:snd_explosion1;
var sndExplodeChannel:SoundChannel;
sndExplode=new snd_explosion1();
sndExplodeChannel=sndExplode.play();
var newExplosion01:explosionEffect=new explosionEffect ;
newExplosion01.x=this.x;
newExplosion01.y=this.y;
_root.explosionContainer.addChild(newExplosion01);
}
private function shipPos()
{
_root.lives -= 1;
_root.mcship.x = 80;
_root.mcship.y = 225;
for each(var i:Enemydude in _root.enemies)
{
removethis();
}
_root.enemies.length = 0;
}
public function removethis():void
{
if(parent) parent.removeChild(this)
removeEventListener(Event.ENTER_FRAME, entFrame);
}
}
}
EDIT: And this is the code I now have that relates to the Enemydude in my main timeline, quite sorry about all this.
var enemies:Array = [];
var Shipheight:Number = 300;
var Enemytime:int = 0;
var Enemylimit:int = 16;
if (Enemytime<Enemylimit)
{
Enemytime ++;
}
else
{
var newEnemy01 = new Enemydude();
newEnemy01.y = Shipheight;
newEnemy01.x = stage.stageWidth + 64;
addChild(newEnemy01);
enemies.push(newEnemy01);
Enemytime = 0
function shipY(event:Event):void
{
Shipheight = Math.ceil(Math.random()* 250) + 80;
}
Thank you for your help in advance, any advice is appreciated.
I suggest storing your enemies in an Array.
For example, create the array enemies:
var enemies:Array = [];
And then amend your code to:
else
{
var newEnemy01 = new Enemydude();
newEnemy01.y = Shipheight;
newEnemy01.x = stage.stageWidth + 64;
addChild(newEnemy01);
enemies.push(newEnemy01);
Enemytime = 0;
}
That way you can remove all of the enemies using this new array:
for each(var i:Enemydude in enemies)
{
i.remove(); // Or whatever function Enemydude has to remove itself.
}
// Empty the enemies Array.
enemies.length = 0;
Here's the .remove() method you could make for Enemydude:
public function remove():void
{
if(parent) parent.removeChild(this);
// Remove any event listeners etc from this object.
}
A common and easy way of doing this is to create a subcontainer to hold the objects and destroy this object instead. It makes easy for some collision checks too, since you can use the holder object to make one check against the player.
If you don't want to create this, you can use an array or a vector to store references to this objects, what makes easy to traverse the list.
I persoally recommend the vector aprouch:
var enemyList:Vector.<Enemy> = new Vector.<Enemy>();
Then you can loop almost like an array (as Marty Wallace showed on his answer):
for each(var e:Enemy in enemyList) {
container.removeChild(e);
}
enemyList.length = 0; // empty vector
Vectors are a bit slower than normal arrays, but are type safe. The difference in performance is almost negligible in most cases.