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);
Related
I'm using a tutorial I found on Google - which works well. However, I have a few issues to make it work how I would like. This code uses a MovieClip for the card faces with the back of the card on frame1 and 2-17 different pictures or movieclips.
The questions are - Is there a way to get the ActionScript to choose from the whole array? But still produce pairs to choose from. As it stands now - If I select the game to be 4 across by 2 down (8 cards in total) It has the back of card (frame1) and will then randomly select, but only from frames 2-5 . If I modify these lines...
public function MatchingGameObject10():void {
// make a list of card numbers
var cardlist:Array = new Array();
for(var i:uint=0;i<boardWidth*boardHeight/2;i++) {
cardlist.push(i);
cardlist.push(i);
}
to
public function MatchingGameObject10():void {
// make a list of card numbers
var cardlist:Array = new Array(0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17);
}
I get random cards - but no pairs...
If I can ask another question here - it is - how to add a seperate sound to each card..So if it shows a Bee - the Bee.mp3 is played.. Here's the whole code..
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.media.Sound;
import flash.media.SoundChannel;
public class MatchingGameObject10 extends MovieClip {
// game constants
private static const boardWidth:uint = 4;
private static const boardHeight:uint = 2;
private static const cardHorizontalSpacing:Number = 500;
private static const cardVerticalSpacing:Number = 700;
private static const boardOffsetX:Number = 50;
private static const boardOffsetY:Number = 70;
private static const pointsForMatch:int = 10;
private static const pointsForMiss:int = -1;
// variables
private var firstCard:Card10;
private var secondCard:Card10;
private var cardsLeft:uint;
private var gameScore:int;
private var gameStartTime:uint;
private var gameTime:uint;
// text fields
private var gameScoreField:TextField;
private var gameTimeField:TextField;
// timer to return cards to face-down
private var flipBackTimer:Timer;
// set up sounds
var theFirstCardSound:FirstCardSound = new FirstCardSound();
var theMissSound:MissSound = new MissSound();
var theMatchSound:MatchSound = new MatchSound();
// initialization function
public function MatchingGameObject10():void {
// make a list of card numbers
var cardlist:Array = new Array();
for(var i:uint=0;i<boardWidth*boardHeight/2;i++) {
cardlist.push(i);
cardlist.push(i);
}
// create all the cards, position them, and assign a randomcard face to each
cardsLeft = 0;
for (var x:uint=0; x<boardWidth; x++) {// horizontal
for (var y:uint=0; y<boardHeight; y++) {// vertical
var c:Card10 = new Card10();// copy the movie clip
c.stop();// stop on first frame
c.x = x*cardHorizontalSpacing+boardOffsetX;// set position
c.y = y*cardVerticalSpacing+boardOffsetY;
var r:uint = Math.floor(Math.random()*cardlist.length);// get a random face
c.cardface = cardlist[r];// assign face to card
cardlist.splice(r,1);// remove face from list
c.addEventListener(MouseEvent.CLICK,clickCard);// have it listen for clicks
c.buttonMode = true;
addChild(c);// show the card
cardsLeft++;
}
}
// set up the score
gameScoreField = new TextField();
addChild(gameScoreField);
gameScore = 0;
showGameScore();
// set up the clock
gameTimeField = new TextField();
gameTimeField.x = 450;
addChild(gameTimeField);
gameStartTime = getTimer();
gameTime = 0;
addEventListener(Event.ENTER_FRAME,showTime);
}
// player clicked on a card
public function clickCard(event:MouseEvent) {
var thisCard:Card10 = (event.target as Card10); // what card?
if (firstCard == null) { // first card in a pair
firstCard = thisCard; // note it
thisCard.startFlip(thisCard.cardface+2);
playSound(theFirstCardSound);
} else if (firstCard == thisCard) { // clicked first card again
firstCard.startFlip(1);
firstCard = null;
playSound(theMissSound);
} else if (secondCard == null) { // second card in a pair
secondCard = thisCard; // note it
thisCard.startFlip(thisCard.cardface+2);
// compare two cards
if (firstCard.cardface == secondCard.cardface) {
// remove a match
removeChild(firstCard);
removeChild(secondCard);
// reset selection
firstCard = null;
secondCard = null;
// add points
gameScore += pointsForMatch;
showGameScore();
playSound(theMatchSound);
// check for game over
cardsLeft -= 2; // 2 less cards
if (cardsLeft == 0) {
MovieClip(root).gameScore = gameScore;
MovieClip(root).gameTime = clockTime(gameTime);
MovieClip(root).gotoAndStop("gameover");
}
} else {
gameScore += pointsForMiss;
showGameScore();
playSound(theMissSound);
flipBackTimer = new Timer(2000,1);
flipBackTimer.addEventListener(TimerEvent.TIMER_COMPLETE,returnCards);
flipBackTimer.start();
}
} else { // starting to pick another pair
returnCards(null);
playSound(theFirstCardSound);
// select first card in next pair
firstCard = thisCard;
firstCard.startFlip(thisCard.cardface+2);
}
}
// return cards to face-down
public function returnCards(event:TimerEvent) {
firstCard.startFlip(1);
secondCard.startFlip(1);
firstCard = null;
secondCard = null;
flipBackTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,returnCards);
}
public function showGameScore() {
gameScoreField.text = "Score: "+String(gameScore);
}
public function showTime(event:Event) {
gameTime = getTimer()-gameStartTime;
gameTimeField.text = "Time: "+clockTime(gameTime);
}
public function clockTime(ms:int) {
var seconds:int = Math.floor(ms/1000);
var minutes:int = Math.floor(seconds/60);
seconds -= minutes*60;
var timeString:String = minutes+":"+String(seconds+100).substr(1,2);
return timeString;
}
public function playSound(soundObject:Object) {
var channel:SoundChannel = soundObject.play();
}
}
}
Here's Card10 class
package {
import flash.display.*;
import flash.events.*;
public dynamic class Card extends MovieClip {
private var flipStep:uint;
private var isFlipping:Boolean = false;
private var flipToFrame:uint;
// begin the flip, remember which frame to jump to
public function startFlip(flipToWhichFrame:uint) {
isFlipping = true;
flipStep = 10;
flipToFrame = flipToWhichFrame;
this.addEventListener(Event.ENTER_FRAME, flip);
}
// take 10 steps to flip
public function flip(event:Event) {
flipStep--; // next step
if (flipStep > 5) { // first half of flip
this.scaleX = .20*(flipStep-6);
} else { // second half of flip
this.scaleX = .20*(5-flipStep);
}
// when it is the middle of the flip, go to new frame
if (flipStep == 5) {
gotoAndStop(flipToFrame);
}
// at the end of the flip, stop the animation
if (flipStep == 0) {
this.removeEventListener(Event.ENTER_FRAME, flip);
}
}
}
}
So without completely re-factoring how this game works, the best way to make it dynamic based off the amount of frames (card faces) in your Card10 Clip, is change this code:
var cardlist:Array = new Array();
for(var i:uint=0;i<boardWidth*boardHeight/2;i++) {
cardlist.push(i);
cardlist.push(i);
}
To the following:
var allCards:Array = new Array(); //an array of all available frame numbers
var cardlist:Array = new Array(); //an array of just those cards to show
var tmpCard:Card10 = new Card10(); //create a temporary card for the sole purpose of counting how many frames it has
var i:int;
//populate the array with all the frames from the Card MC
for (i = 0; i < tmpCard.totalFrames;i++) {
allCards.push(i);//add card frame to allCards array
}
//now create the list of cards to show (since the amount of cards may be more than the amount you want to show
for (i = 0; i < (boardWidth * boardHeight) / 2; i++) {
var cardIndex:int = Math.floor(Math.random() * allCards.length);// get a random card from the all card list
//add the card twice (so there is a pair) in the list of cards to show
cardlist.push(cardIndex);
cardlist.push(cardIndex);
//remove it from the all cards array so it doesn't come up again in the random bit above
allCards.splice(cardIndex,1);
}
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 :)
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).
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.
I am using math.random to randomly drop objects from the top of the stage. I had it working with one object. But as I wanted to increase the number to 6 objects, I added the following code: But I am "stuck" and so are the 6 objects at the top of the stage. What am I doing wrong here? I appreciate the help.
private function bombInit(): void {
roachBombArray = new Array();
for (var i:uint =0; i < numBombs; i++) {
roachBomb= new RoachBomb();
roachBomb.x = Math.random() * stage.stageWidth;
roachBomb.vy = Math.random() * 2 -1;
roachBomb.y = -10;
addChild(roachBomb);
roachBombArray.push(roachBomb);
}
addEventListener(Event.ENTER_FRAME, onEntry);
}
private function onEntry(event:Event):void {
for (var i:uint = 0; i< numBombs; i++) {
var roachBomb = roachBombArray[i];
vy += ay;
roachBombArray[i] += vy;
if (roachBombArray[i] > 620) {
removeChild(roachBombArray[i]);
removeEventListener(Event.ENTER_FRAME, onEntry);
You are trying to add the velocity to the RoachBomb rather than to the RoachBomb y position.
roachBombArray[i] += vy;
should be
roachBombArray[i].y += vy;
Additionally you create a local variable:
var roachBomb = roachBombArray[i];
but you never manipulate it.
Perhaps you meant to do something like this?
var roachBomb:RoachBomb = roachBombArray[i]; // I added the type to the local variable
roachBomb.vy += ay;
roachBomb.y += vy; // Manipulate the local variable
if (roachBomb.y > 620) {
removeChild(roachBomb);
}
You're removing your enterFrame listener when the first bomb goes off the bottom, at which point you're no longer listening for ENTER_FRAME events and updating any of your bombs.
You don't want to remove this listener until you're done animating ALL the bombs.
UPDATE: How I would expect things to look, incorperating Ethan's observation that you ought to use the local roachBomb that you declare...
public class BombDropper extends Sprite {
private static const GRAVITY:int = 1; // Set gravity to what you want in pixels/frame^2
private static const BOTTOM_OF_SCREEN:int = 620;
private var numBombs:int = 6;
private var roachBombArray:Array;
// ... constructor and other class stuff here
private function bombInit(): void
{
roachBombArray = new Array();
for (var i:int =0; i < numBombs; ++i)
{
var roachBomb:RoachBomb = new RoachBomb();
roachBomb.x = Math.random() * stage.stageWidth;
roachBomb.vy = Math.random() * 2 -1;
roachBomb.y = -10;
this.addChild(roachBomb);
roachBombArray.push(roachBomb);
}
this.addEventListener(Event.ENTER_FRAME, onEntry);
}
private function onEntry(event:Event):void
{
for each ( var roachBomb:RoachBomb in roachBombArray)
{
roachBomb.vy += GRAVITY;
roachBomb.y += vy;
if (roachBomb.y > BOTTOM_OF_SCREEN)
{
this.removeChild(roachBomb);
roachBombArray.splice(roachBombArray.indexOf(roachBomb),1);
if (roachBombArray.length == 0)
{
this.removeEventListener(Event.ENTER_FRAME, onEntry);
}
}
}
}
}