Trouble creating multiple objects (Arrays) in Flash - arrays

I'm making a basic Galaga type game in Flash and have been running into issues. This is my first time really messing with ActionScript.
I created an Array for my Enemies and would like to know how I would go about having them spawn in their own respective locations, like in Galaga and then have them move uniformly form left to right while descending once reaching the edge of the stage.
Game
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class SpaceVigilanteGame extends MovieClip
{
public var army:Array;
public var avatar:Avatar;
public var gameTimer:Timer;
public var useMouseControl:Boolean;
public var rightKeyIsBeingPressed:Boolean;
public var leftKeyIsBeingPressed:Boolean;
var gameWidth:int = 0;
var gameHeight:int = 0;
public function SpaceVigilanteGame()
{ useMouseControl = false;
leftKeyIsBeingPressed = false;
rightKeyIsBeingPressed = false;
army = new Array();
var newEnemy = new Enemy( 60, 30 );
army.push( newEnemy );
addChild( newEnemy );
avatar = new Avatar();
addChild( avatar );
if ( useMouseControl )
{
avatar.x = mouseX;
avatar.y = mouseY;
}
else
{
avatar.x = 50;
avatar.y = 400;
}
gameWidth = stage.stageWidth;
gameHeight = stage.stageHeight;
gameTimer = new Timer( 25 );
gameTimer.addEventListener( TimerEvent.TIMER, moveEnemy );
gameTimer.addEventListener( TimerEvent.TIMER, moveAvatar );
gameTimer.start();
stage.addEventListener( KeyboardEvent.KEY_DOWN, onKeyPress );
stage.addEventListener( KeyboardEvent.KEY_UP, onKeyRelease );
function onKeyPress( keyboardEvent:KeyboardEvent ):void
{
if ( keyboardEvent.keyCode == Keyboard.RIGHT )
{
rightKeyIsBeingPressed = true;
}
else if ( keyboardEvent.keyCode == Keyboard.LEFT )
{
leftKeyIsBeingPressed = true;
}
}
function onKeyRelease( keyboardEvent:KeyboardEvent ):void
{
if ( keyboardEvent.keyCode == Keyboard.RIGHT )
{
rightKeyIsBeingPressed = false;
}
else if (keyboardEvent.keyCode ==Keyboard.LEFT )
{
leftKeyIsBeingPressed = false;
}
}
}
public function moveEnemy( timerEvent:TimerEvent ):void
{
for each ( var enemy:Enemy in army )
{
}
//enemy.moveDownABit();
if(enemy.x+enemy.width+2<=gameWidth)
{
enemy.moveRight();
}
else if(enemy.y+enemy.height+2<=gameHeight)
{
enemy.moveDown();
}
else if(enemy.x-2>=0)
{
enemy.moveLeft();
}
else if(enemy.y-2>=0)
{
enemy.moveUp();
}
}
public function moveAvatar( timerEvent:TimerEvent ):void
{
if ( useMouseControl )
{
avatar.x = mouseX;
avatar.y = mouseY;
}
else if ( rightKeyIsBeingPressed )
{
avatar.moveRight();
}
else if ( leftKeyIsBeingPressed )
{
avatar.moveLeft();
}
}
}
}
Enemy Class
package
{
import flash.display.MovieClip;
public class Enemy extends MovieClip
{
public function Enemy( startX:Number, startY:Number )
{
x = startX;
y = startY;
}
public function moveRight():void
{
x = x + 2;
}
public function moveDown():void
{
y = y + 2;
}
public function moveLeft():void
{
x = x - 2;
}
public function moveUp():void
{
y = y - 2;
}
}
}

I would suggest that during the enemy instantiation (of which there seems to be only one), you should be setting the locations respective of one another.
as an example:
your code currently does this:
var newEnemy = new Enemy( 60, 30 );
army.push( newEnemy );
addChild( newEnemy );
Perhaps it should do something like this:
for(var x:int = 0; x< ARMY_WIDTH; x++)
{
for(var y:int = 0; y < ARMY_HEIGHT; y++)
{
army.push(new Enemy(60 + x * X_GAP, 30 + y *Y_GAP));
this.addChild(army[army.length-1]);
}
}
Now, I've made a lot of assumptions in the above code; I've invented constants that you may not have, and I've only solved your immediate problem. Ideally you're going to need to look at more advanced solutions for your issue, something like a factory class that creates your enemies for you, or recycles them from a pool of enemies.
However, you're just starting out and you will figure a lot of this stuff out in time. Good luck in your project and I hope you keep up developing your skills :)

Related

How to create multiple instances of the same class in as3?

Noob question. Ok, so I'm trying to create two instances of my notes (it's an imported pic) class at separate x and y coordinates, then I want both of them to move right. Right now I programmed a loop, and the loop works OK, but it only keeps the last instance that was created. Here's my code. I really appreciate any help that anyone can give. Thanks!
package
{
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.utils.getDefinitionByName;
[Frame(factoryClass="Preloader")]
public class Main extends Sprite
{
private var speed:int = 8;
[Embed(source="../lib/Dodgethis.jpg")]
public var Notes:Class;
public var numnotes:Number;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
stage.addEventListener(KeyboardEvent.KEY_DOWN, testevent);
}
private function testevent(e:Event = null):void {
trace("testevent has run");
appear(350, 250);
//ap2(150, 150)
//addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
private function appear(x:Number, y:Number) {
var arr1:Array = new Array;
numnotes = 4;
for (var i = 0; i < numnotes; i++)
{
trace (i);
var nbm:Bitmap = new Notes;
if (i == 0) {
this.x = 400;
this.y = 400;
addChild(nbm);
trace ("1 should be different");
} else {
trace ("this is working");
this.x = 150;
this.y = 150;
addChild(nbm);
arr1.push(nbm);
You have created 4 Notes, but their positions are same point (0,0).

Creating Enemy Cone of vision

I am trying to create a cone of vision for my enemy class. Right now it checks to see if the player is within a radius before moving towards them and will move around randomly if they are not. I want to give it vision so the enemy does not always rotate towards the player.
Enemy Class
package
{
import flash.automation.ActionGenerator;
import flash.events.Event;
import flash.geom.Point;
public class Enemy extends GameObject
{
var isDead:Boolean = false;
var speed:Number = 3;
var originalValue:Number = 50;
var changeDirection:Number = originalValue;
var checkDirection:Number = 49;
var numberGen:Number;
//var startTime:int = getTimer();
//var $timer = getTimer();
//var myTimer:int = getTimer();
//var moveTimer:int = timer - $timer;
public function Enemy()
{
super();
target = target_mc;
}
override public function update():void
{
movement();
}
private function movement():void
{
if (changeDirection >= 0)
{
if (changeDirection > checkDirection)
{
numberGen = (Math.random() * 360) / 180 * Math.PI;
}
var velocity:Point = new Point();
var $list:Vector.<GameObject > = getType(Player);
var $currentDistance:Number = Number.MAX_VALUE;
for (var i:int = 0; i < $list.length; i++)
{
var currentPlayer:GameObject = $list[i];
if (MathUtil.isWithinRange(currentPlayer.width,currentPlayer.x,currentPlayer.y,width,x,y))
{
var $delta:Point = new Point ;
$delta.x = currentPlayer.x - x;
$delta.y = currentPlayer.y - y;
if ($currentDistance > $delta.length)
{
$currentDistance = $delta.length;
velocity = $delta;
velocity.normalize(speed);
}
}
}
if(velocity.length == 0)
{
velocity = Point.polar(2, numberGen);
}
changeDirection--;
if (changeDirection == 0)
{
changeDirection = originalValue;
}
}
velocity.x = Math.floor(velocity.x * 10) * .1;
velocity.y = Math.floor(velocity.y * 10) * .1;
moveBy([Wall, Door], velocity.x, velocity.y, collides_mc);
var $collides:GameObject = collision([Player]);
if ($collides != null)
{
destroy();
}
if ($collides == null)
{
$collides = collision([Player],this);
if ($collides != null)
{
$collides.destroy();
}
}
rotation = (Math.atan2(velocity.y, velocity.x) * 180 / Math.PI);
collides_mc.rotation = -rotation;
trace($collides);
}
override public function onCollideX($collision:GameObject):void
{
}
override public function onCollideY($collision:GameObject):void
{
}
}
}
GameObject Class, which contains all the functions and Enemy extends it
package
{
import flash.display.DisplayObject;
import flash.events.Event;
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.sensors.Accelerometer;
import flashx.textLayout.elements.ListElement;
public class GameObject extends MovieClip
{
static public var list:Vector.<GameObject> = new Vector.<GameObject>;
protected var hitBox:Sprite;
public var target:MovieClip;
public function GameObject()
{
target=this;
list.push(this);
}
public function update():void
{
}
public function collision(typesColliding:Array, $target:DisplayObject = null):GameObject
{
if($target == null)
$target = target;
for (var i:int = list.length - 1; i >= 0; i--)
{
var item:GameObject = list[i], found:Boolean = false;
for (var f:int = typesColliding.length - 1; f >= 0; f--)
{
if (item is typesColliding[f])
{
found = true;
break;
}
}
if (found && $target.hitTestObject(item.target) && this != item)
{
return item;
}
}
return null;
}
public function moveBy(typesColliding:Array, $x:Number = 0, $y:Number = 0, $target:DisplayObject = null):void
{
var $collision:GameObject;
x += $x;
if (($collision = collision(typesColliding, $target)) != null)
{
x -= $x;
onCollideX($collision);
}
y += $y;
if (($collision = collision(typesColliding, $target)) != null)
{
y -= $y;
onCollideY($collision);
}
}
public function onCollideX($collision:GameObject):void
{
}
public function onCollideY($collision:GameObject):void
{
}
public function getType($class:Class):Vector.<GameObject>
{
var $list:Vector.<GameObject> = new Vector.<GameObject>;
for (var i:int = 0; i < list.length; i++)
{
if (list[i] is $class)
{
$list.push(list[i]);
}
}
return $list;
}
public function destroy():void
{
var indexOf:int = list.indexOf(this);
if (indexOf > -1)
list.splice(indexOf, 1);
if (parent)
parent.removeChild(this);
trace("removing item: "+this+" list: " + list.length + ": " + list);
}
}
}
Any help would be appreciated, thank you.
Changing radius of vision to the cone of vision simply requires computing (after checking the distance) the angle between the direction enemy is facing and the player. If this angle is smaller then some T, then it is in the cone of vision of angle 2T (due to symmetry).
This obviously ignores any walls/obstacles that should limit vision, but it should give you the general idea.

How do i get Object index in an array

I have seen many threads about this but my problem doesn't solved. This may be a simple way but i have no idea...
I'm trying to get Objects indices in an array like so :
var test:Array = new Array();
for (var row:Number = 0; row < 2; row++) {
test[row] = [];
for (var column:Number = 0; column < 3; column++) {
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
test[row][column] = new ballShape(column, column, row);
addChild(test[row][column]);
}
}
function objClicked(evt:MouseEvent):void {
// Here must return Object index in array
}
P.S :
I can get items index in int array, but i don't know about objects.
Any ideas would be appreciated.
Edit :
ballShape.as
package {
import flash.display.Graphics;
import flash.display.Sprite;
import flash.events.MouseEvent;
import fl.motion.Color;
public class ballShape extends Sprite {
private var shapeId:uint;
private var currentPosition:uint;
private var arrayPosition:uint;
private var color:Number;
public function ballShape(Id:uint, currPos:uint, arrPos:uint) {
setId(Id);
setArrayPos(arrPos);
setCurrentPos(currPos);
//trace("Array : " + arrPos);
//trace("Curr : " + currPos);
if (arrPos == 0) {
var posX:uint = 60;
} else {
var posX:uint = (arrPos + 1) * 60;
}
if (currPos == 0) {
var posY:uint = 42;
} else {
var posY:uint = (currPos + 1) * 42;
}
if (arrPos == 0) {
color = 0xFF0000;
} else {
color = 0x00FF00;
}
graphics.beginFill(color, 1.0);
graphics.drawCircle(posX, posY, 20);
graphics.endFill();
this.addEventListener(MouseEvent.CLICK, Clicked);
}
public function setId(Id:uint):void {
shapeId = Id;
}
public function getId():uint {
return shapeId;
}
public function Clicked(evt:MouseEvent):void {
//return getId();
trace("Ball id is " + getId());
trace("Array id is " + getArrayPos());
trace("PositionInArray id is " + getCurrentPos());
//return arrayPosition;
}
public function setCurrentPos(Pos:uint):void {
currentPosition = Pos;
}
public function getCurrentPos():uint {
return currentPosition;
trace(currentPosition);
}
public function setArrayPos(arrayPos:uint):void {
arrayPosition = arrayPos;
}
public function getArrayPos():uint {
return arrayPosition;
trace(arrayPosition);
}
public function addBead(arrayId, currPos):void {
}
}
}
I would suggest adding row and column as public variables in your ballShape class.
That way you can get them like this:
function objClicked(evt:MouseEvent):void {
trace(ballShape(evt.target).getCurrentPos(), ballShape(evt.target).getArrayPos());
}
Maybe turn this two lines around:
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
test[row][column] = new ballShape(column, column, row);
to be :
test[row][column] = new ballShape(column, column, row);
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
Try something like:
protected function objClicked(e:MouseEvent):void {
for (var row: int=0; row < test.length; row++) {
var column:int = (test[row] as Array).indexOf(e.currentTarget);//use currentTarget so you don't try to match on internal Interactive Objects!
if (column>-1) {
trace(row, column);
return;//or break, if you need to do something else below this loop
}
}
}

Positioning a movieclip onto another movieclip

I'm creating a game where if you hit a zombie the zombie dies and his head is sent back in the direction you hit. I have two movieclips the zombie and the zombie head. Once the zombie is hit it will play its dying animation and remove itself and at the same time the zombie head will be added to the dying zombie and be blown back. I have done the code for the hittest and the zombie dying and respawning but I can't seem to position and add the head to the dying zombie when it is hit. How can I do this. I thought it will be like this, I added this in the PlayDeathAnimation function in the zombie class but did not work:
for (var i=0; i < MovieClip(parent).zombies.length; ++i)
{
var zh = new ZombieHead();
zh.x = MovieClip(parent).zombies[i].x;
zh.y = MovieClip(parent).zombies[i].y;
zh.rotation = MovieClip(parent).zombies[i].rotation;
addChild(zh);
}
I have 4 classes
Player
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
import flash.display.Graphics;
import flash.utils.setTimeout;
public class Player extends MovieClip
{
//Player Setting
var walkSpeed:Number = 4;
var walkRight:Boolean = false;
var walkLeft:Boolean = false;
var walkUp:Boolean = false;
var walkDown:Boolean = false;
var attacking:Boolean = false;
var attackRange:int = 100;
var attackAngle:int = 30;
public function Player()
{
stage.addEventListener(KeyboardEvent.KEY_DOWN,walk);
addEventListener(Event.ENTER_FRAME,Update);
stage.addEventListener(KeyboardEvent.KEY_UP,stopWalk);
stage.addEventListener(MouseEvent.CLICK,attack);
// The lines below draw a preview of your attack area
graphics.beginFill(0x00ff00, 0.2);
graphics.lineTo(attackRange*Math.cos((rotation-attackAngle)/180*Math.PI),attackRange*Math.sin((rotation-attackAngle)/180*Math.PI));
graphics.lineTo(attackRange*Math.cos((rotation+attackAngle)/180*Math.PI),attackRange*Math.sin((rotation+attackAngle)/180*Math.PI));
graphics.endFill();
}
function walk(event:KeyboardEvent)
{
//When Key is Down
if (event.keyCode == 68)
{
walkRight = true;
}
if (event.keyCode == 87)
{
walkUp = true;
}
if (event.keyCode == 65)
{
walkLeft = true;
}
if (event.keyCode == 83)
{
walkDown = true;
}
}
function Update(event:Event)
{
//if attacking is true then key moves are false;
if ((attacking == true))
{
walkRight = false;
walkLeft = false;
walkUp = false;
walkDown = false;
// see if the zombie is in the cone
for (var i:int=MovieClip(parent).zombies.length-1; i>=0; i--)
{
if (inAttackCone(MovieClip(parent).zombies[i]))
{
if (hitTestObject(MovieClip(parent).zombies[i]))
{
//attacking = true;
MovieClip(parent).zombies[i].zombieDead = true;
}
}
}
}
else if ((attacking == false))
{
//Else if attacking is false then move and rotate to mouse;
var dx = parent.mouseX - x;
var dy = parent.mouseY - y;
var angle = Math.atan2(dy,dx) / Math.PI * 180;
rotation = angle;
if ((walkRight == true))
{
x += walkSpeed;
gotoAndStop(2);
}
if ((walkUp == true))
{
y -= walkSpeed;
gotoAndStop(2);
}
if ((walkLeft == true))
{
x -= walkSpeed;
gotoAndStop(2);
}
if ((walkDown == true))
{
y += walkSpeed;
gotoAndStop(2);
}
}
}
//Calculate the distance between the two
public function distanceBetween(player:MovieClip,zombies:MovieClip):Number
{
for (var i:int=MovieClip(parent).zombies.length-1; i>=0; i--)
{
var dx:Number = x - MovieClip(parent).zombies[i].x;
var dy:Number = y - MovieClip(parent).zombies[i].y;
}
return Math.sqrt(((dx * dx) + dy * dy));
}
public function angleDifference(a:Object, b:Object):Number
{
var dx:Number = b.x - a.x;
var dy:Number = b.y - a.y;
var ang:Number = (a.rotation/180*Math.PI)-Math.atan2(dy, dx);
while (ang>Math.PI)
{
ang -= 2 * Math.PI;
}
while (ang<-Math.PI)
{
ang += 2 * Math.PI;
}
return Math.abs(ang*180/Math.PI);
}
function inAttackCone(enemy:MovieClip):Boolean
{
var distance:Number = distanceBetween(this,enemy);
distance -= enemy.width / 2;// account for the enemy's size
if (distance < attackRange)
{
// In range, check angle
if (angleDifference(this,enemy)<attackAngle)
{
return true;
}
}
return false;
}
function stopWalk(event:KeyboardEvent)
{
if ((attacking == false))
{
if (event.keyCode == 68)
{
event.keyCode = 0;
walkRight = false;
gotoAndStop(1);
}
if (event.keyCode == 87)
{
event.keyCode = 0;
walkUp = false;
gotoAndStop(1);
}
if (event.keyCode == 65)
{
event.keyCode = 0;
walkLeft = false;
gotoAndStop(1);
}
if (event.keyCode == 83)
{
event.keyCode = 0;
walkDown = false;
gotoAndStop(1);
}
}
}
function attack(event:MouseEvent)
{
if ((attacking == false))
{
attacking = true;
gotoAndStop(3);
}
}
}
}
Zombies
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.geom.Point;
public class Zombie extends MovieClip
{
var walkSpeed:Number = 2;
var target:Point;
public var zombieDead:Boolean = false;
public function Zombie()
{
//set target location of Zombie
target = new Point(Math.random() * 500,Math.random() * 500);
}
function loop()
{
if (zombieDead == true)
{
playDeathAnimation();
}
else if (zombieDead == false)
{
gotoAndStop(1);
//Point Zombie at its target
var dx = MovieClip(root).Player01.x - x;
var dy = MovieClip(root).Player01.y - y;
var angle = Math.atan2(dy,dx) / Math.PI * 180;
rotation = angle;
//Move in the direction the zombie is facing
x = x+Math.cos(rotation/180*Math.PI)*walkSpeed;
y = y+Math.sin(rotation/180*Math.PI)*walkSpeed;
//Calculate the distance to target
var hyp = Math.sqrt((dx*dx)+(dy*dy));
if (hyp<5)
{
target.x = Math.random() * 500;
target.y = Math.random() * 500;
}
}
}
public function playDeathAnimation()
{
gotoAndStop(2);
}
public function deathAnimationFinishedCallback()
{
for (var i=0; i < MovieClip(parent).zombies.length; ++i)
{
if (MovieClip(parent).zombies[i] == this)
{
MovieClip(parent).zombies.splice(i, 1);
break;
}
}
MovieClip(parent).removeChild(this);
}
}
}
Document Class
package
{
import flash.display.MovieClip;
import flash.events.Event;
public class Game extends MovieClip
{
public var zombies:Array;
public function Game()
{
addEventListener(Event.ENTER_FRAME, update);
zombies = new Array();
}
public function update(e:Event)
{
//Only spawn a Zombie if there are less than number
if (numChildren < 4)
{
//Make a new instance of the Zombie.
var Z = new Zombie();
addChild(Z);
//Position and rotate the zombie
Z.x = Math.random() * stage.stageWidth;
Z.y = Math.random() * stage.stageHeight;
Z.rotation = Math.random() * 360;
zombies.push(Z);
}
for (var count = 0; count<zombies.length; count ++)
{
zombies[count].loop();
}
}
}
}
Zombie Head
package
{
import flash.display.MovieClip;
import flash.events.Event;
public class ZombieHead extends MovieClip
{
var headSpeed:Number = -30;
var friction:Number = 0.9;
public function ZombieHead()
{
// constructor code
addEventListener(Event.ENTER_FRAME,Update);
}
function Update(event:Event)
{
x = x+Math.cos(rotation/180*Math.PI)*headSpeed;
y = y+Math.sin(rotation/180*Math.PI)*headSpeed;
headSpeed *= friction;
if (headSpeed > -0.00001)
{
removeEventListener(Event.ENTER_FRAME,Update);
parent.removeChild(this);
}
else if (x<0 || x > 550 || y < 0 || y > 400)
{
removeEventListener(Event.ENTER_FRAME,Update);
parent.removeChild(this);
}
}
}
}

AS3 - Array Object still being updated?

So in my game I'm using an array of enemies for keeping track of them and updating them and so on - when the player crashes into a enemy its game however, however if the player shoots a bullet that hits the enemy the enemy is deleted. Well thats supposed to be what happens however when the bullet its the enemy it deletes it but for some reason that object is still being updated and can still crash into the player?
How do I go about stopping this?
This is the code that I have in the laser class for checking for collisions
private function loop(e:Event) : void
{
//move bullet up
y -= bulletSpeed;
if (y < 0)
{
removeSelf();
}
for (var i:int = 0; i < AvoiderGame.enemyArray.length; i++)
{
if (hitTestObject(AvoiderGame.enemyArray[i]))
{
AvoiderGame.enemyArray[i].takeHit();
removeSelf();
}
}
}
This is all the code that I have in the enemy class.
package
{
import flash.display.MovieClip;
import flash.display.Stage;
public class Enemy extends MovieClip
{
private var stageRef:Stage;
public function Enemy(startX:Number, startY:Number, stageRef:Stage)
{
this.stageRef = stageRef;
x = startX;
y = startY;
}
public function moveDown():void
{
y = y + (1 + (10 - 1) * Math.random());
switch(Math.round(1 + (2 - 1) * Math.random()))
{
case 1: x = x + (1 + (10 - 1) * Math.random());
break;
case 2: x = x - (1 + (10 - 1) * Math.random());
break;
};
}
public function StayOnScreen():void
{
if (x <= 0)
{
x = 0;
}
else if (x >= stageRef.stageWidth)
{
x = stageRef.stageWidth;
}
else
{
x = x;
}
}
private function removeSelf() : void
{
if (stageRef.contains(this))
{
this.parent.removeChild(this);
delete AvoiderGame.enemyArray[this];
}
}
public function takeHit() : void
{
removeSelf();
}
}
}
This is all the code that I have in the main game.
package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import com.freeactionscript.CollisionTest;
import flash.display.Stage;
import flashx.textLayout.formats.BackgroundColor;
public class AvoiderGame extends MovieClip
{
public static var enemyArray:Array;
public var enemy:Enemy
public var Background:gameBackground;
public var avatar:Avatar;
public var gameTimer:Timer;
private var _collisionTest:CollisionTest;
private var numStars:int = 80;
private var fireTimer:Timer; //causes delay between fires
private var canFire:Boolean = true; //can you fire a laser
public function AvoiderGame()
{
Background = new gameBackground();
addChild(Background);
enemyArray = new Array();
var enemy = new Enemy(Math.round(1 + (500 - 1) * Math.random()), - 2, stage);
enemyArray.push(enemy);
addChild(enemy);
avatar = new Avatar(stage);
addChild(avatar);
avatar.x = stage.stageWidth / 2;
avatar.y = stage.stageHeight / 2;
for (var i:int = 0; i < numStars; i++)
{
stage.addChildAt(new Star(stage), 1);
}
_collisionTest = new CollisionTest();
gameTimer = new Timer(25);
gameTimer.addEventListener(TimerEvent.TIMER, onTick);
gameTimer.start();
fireTimer = new Timer(300, 1);
fireTimer.addEventListener(TimerEvent.TIMER, fireTimerHandler, false, 0, true);
fireTimer.start();
}
public function onTick(timerEvent:TimerEvent):void
{
if (Math.random() < 0.1)
{
var enemy = new Enemy(Math.round(1 + (500 - 1) * Math.random()), - 28, stage);
enemyArray.push(enemy);
addChild(enemy);
}
avatar.UpdateAvatar(canFire);
if (canFire == true)
{
canFire = false;
fireTimer.start();
}
avatar.StayOnScreen();
for each (var enemy:Enemy in enemyArray)
{
enemy.moveDown();
enemy.StayOnScreen();
if (_collisionTest.complex(enemy, avatar))
{
gameTimer.stop();
}
}
}
private function fireTimerHandler(e:TimerEvent) : void
{
//timer ran, we can fire again.
canFire = true;
}
}
I understand that im probably going wrong in the enemy class with the removeSelf() function but how would i go about fixing this?
If you dont get want I mean - there is a playable example of this game on my website using space to shot will destroy the enemy but it will still be in the game?
http://dynamite-andy.co.uk/projects/free-time/as3-avoider-game/
The problem seems to be with this line in the removeSelf() method:
delete AvoiderGame.enemyArray[this];
To delete something from an Array you have to use one the Array class methods that modifies the array rather than the delete keyword.
[EDIT]
In this case, you can use splice(), to remove the enemy from the array:
var enemyIndex:int = this.parent.getChildIndex(this);
this.parent.removeChild(this);
AvoiderGame.enemyArray.splice(enemyIndex, 1);

Resources