How can I change Nested Class in actionscript 3 - actionscript-3

I'm working off an actionscript 3 code that pulls information from other actionscript 3's. The main code is Herbfight and it references 4 others (Bullets, bugs, Goodbugs and Sprayer). Below I'm trying to combine them all into one actionscript. The reason for this is that I want to pull it in as a symbol rather then having the flash file relate to the class.
The problem is it says I can't have nested classes. Any thoughts on how i can fix this? Below is my attempt to combine the code.
Thanks,
J
package {
import flash.display.;
import flash.events.;
import flash.utils.Timer;
import flash.text.TextField;
import flash.text.*;
import flash.utils.getTimer;
import flash.geom.Point;
public class herbfight_v004 extends MovieClip {
private var aagun:Sprayer;
private var airplanes:Array;
private var goodbug:Array;
private var bullets:Array;
private var upArrow, downArrow:Boolean;
private var nextPlane:Timer;
private var nextGbugs:Timer;
private var shotsLeft:int;
private var shotsHit:int;
private var Sprayer:MovieClip
private var Bullets:MovieClip
private var bugs:MovieClip
private var GooodBugs:MovieClip
public function startherbfight_v004() {
// init score
shotsLeft = 20;
shotsHit = 0;
showGameScore();
// create gun
aagun = new Sprayer();
addChild(aagun);
// create object arrays
airplanes = new Array();
bullets = new Array();
goodbug = 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();
setNextGbugs();
public function Sprayer() {
{
// animation time// initial location of gun
this.x = 410;
this.y = 380;
// movement
addEventListener(Event.ENTER_FRAME,moveGun);
}
public function moveGun(event:Event) {
// get time difference
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// current position
var newy = this.y;
// move to the left
if (MovieClip(parent).upArrow) {
newy -= speed*timePassed/1000;
}
// move to the right
if (MovieClip(parent).downArrow) {
newy += speed*timePassed/1000;
}
// check boundaries
if (newy < 65) newy = 65;
if (newy > 380) newy = 380;
// reposition
this.y = newy;
}
// remove from screen and remove events
public function deleteGun() {
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveGun);
}
}
public 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();
}
public 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();
}
}
// plane hit, show explosion
public function planeHit() {
removeEventListener(Event.ENTER_FRAME,movePlane);
MovieClip(parent).removePlane(this);
gotoAndPlay("explode");
}
// delete plane from stage and plane list
public function deletePlane() {
removeEventListener(Event.ENTER_FRAME,movePlane);
MovieClip(parent).removePlane(this);
parent.removeChild(this);
}
}
public 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);
}
public 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
public function deleteBullet() {
MovieClip(parent).removeBullet(this);
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveBullet);
}
}
public function GoodBugs(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 Gbugs
this.gotoAndStop(Math.floor(Math.random()*2+1));
// set up animation
addEventListener(Event.ENTER_FRAME,moveGbugs);
lastTime = getTimer();
}
public function moveGbugs(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move Gbugs
this.x += dx*timePassed/2000;
// check to see if off screen
if ((dx < 0) && (x < -50)) {
deleteGbugs();
} else if ((dx > 0) && (x > 350)) {
deleteGbugs();
}
}
// Gbugs hit, show explosion
public function GbugsHit() {
removeEventListener(Event.ENTER_FRAME,moveGbugs);
MovieClip(parent).removeGbugs(this);
gotoAndPlay("explode");
}
// delete Gbugs from stage and Gbugs list
public function deleteGbugs() {
removeEventListener(Event.ENTER_FRAME,moveGbugs);
MovieClip(parent).removeGbugs(this);
parent.removeChild(this);
}
}
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() > .2) {
var side:String = "left";
} else {
side = "right";
}
var altitude:Number = Math.random()*280+80;
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 setNextGbugs() {
nextGbugs = new Timer(1000+Math.random()*1000,1);
nextGbugs.addEventListener(TimerEvent.TIMER_COMPLETE,newGbugs);
nextGbugs.start();
}
public function newGbugs(event:TimerEvent) {
// random side, speed and altitude
if (Math.random() > .2) {
var side:String = "left";
} else {
side = "right";
}
var altitude:Number = Math.random()*280+80;
var speed:Number = Math.random()*150+150;
// create Gbugs
var p:GoodBugs = new GoodBugs(side,speed,altitude);
addChild(p);
goodbug.push(p);
// set time for next Gbugs
setNextGbugs();
}
// 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 GoodBugsNum:int= goodbug.length-1; GoodBugsNum>=0; GoodBugsNum--) {
if (bullets[bulletNum].hitTestObject(goodbug [GoodBugsNum])) {
goodbug [GoodBugsNum]. GbugsHit();
bullets[bulletNum].deleteBullet();
shotsHit--;
showGameScore();
break;
}
}
}
if ((shotsLeft == 0) && (bullets.length == 0)) {
endGame();
}
}
// key pressed
public function keyDownFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
upArrow = true;
} else if (event.keyCode == 40) {
downArrow = true;
} else if (event.keyCode == 32) {
fireBullet();
}
}
// key lifted
public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
upArrow = false;
} else if (event.keyCode == 40) {
downArrow = 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 plane from the array
public function removeGbugs(Gbugs:GoodBugs) {
for(var i in goodbug) {
if (goodbug[i] == Gbugs) {
goodbug.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= goodbug.length-1;i>=0;i--) {
goodbug [i].deleteGbugs();
}
airplanes = null;
goodbug = 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;
nextGbugs.stop();
nextGbugs = null;
gotoAndStop("gameover");
}
}
}

Related

boundares - if object is past, delete object

I have a code below that has rocks moving from left to right, I would like to create a boundary for them that they can only move a certain way in on the stage, once they get past this point they delete. I have tried to write this up under the Wrap Rocks and Delete Rocks section, but it's not working and it's not giving me any errors. Does anyone have any thoughts that might help me?
let me know if you need to see more code:
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.geom.Point;
public class SpaceRocks_v002 extends MovieClip {
static const shipRotationSpeed:Number = .1;
static const rockSpeedStart:Number = .03;
static const rockSpeedIncrease:Number = .02;
static const missileSpeed:Number = .2;
static const thrustPower:Number = .15;
static const shipRadius:Number = 20;
static const startingShips:uint = 3;
// game objects
private var ship:Ship;
private var rocks:Array;
private var missiles:Array;
// animation timer
private var lastTime:uint;
// arrow keys
private var rightArrow:Boolean = false;
private var leftArrow:Boolean = false;
private var upArrow:Boolean = false;
// ship velocity
private var shipMoveX:Number;
private var shipMoveY:Number;
// timers
private var delayTimer:Timer;
private var shieldTimer:Timer;
// game mode
private var gameMode:String;
private var shieldOn:Boolean;
// ships and shields
private var shipsLeft:uint;
private var shieldsLeft:uint;
private var shipIcons:Array;
private var shieldIcons:Array;
private var scoreDisplay:TextField;
// score and level
private var gameScore:Number;
private var gameLevel:uint;
// sprites
private var gameObjects:Sprite;
private var scoreObjects:Sprite;
// start the game
public function startSpaceRocks_v002():void {
// set up sprites
gameObjects = new Sprite();
addChild(gameObjects);
scoreObjects = new Sprite();
addChild(scoreObjects);
// reset score objects
gameLevel = 1;
shipsLeft = startingShips;
gameScore = 0;
createShipIcons();
createScoreDisplay();
// set up listeners
addEventListener(Event.ENTER_FRAME,moveGameObjects);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
// start
gameMode = "delay";
shieldOn = false;
missiles = new Array();
nextRockWave(null);
newShip(null);
}
// SCORE OBJECTS
// draw number of ships left
public function createShipIcons() {
shipIcons = new Array();
for(var i:uint=0;i<shipsLeft;i++) {
var newShip:ShipIcon = new ShipIcon();
newShip.x = 20+i*15;
newShip.y = 375;
scoreObjects.addChild(newShip);
shipIcons.push(newShip);
}
}
// draw number of shields left
public function createShieldIcons() {
shieldIcons = new Array();
for(var i:uint=0;i<shieldsLeft;i++) {
var newShield:ShieldIcon = new ShieldIcon();
newShield.x = 530-i*15;
newShield.y = 375;
scoreObjects.addChild(newShield);
shieldIcons.push(newShield);
}
}
// put the numerical score at the upper right
public function createScoreDisplay() {
scoreDisplay = new TextField();
scoreDisplay.x = 480;
scoreDisplay.y = 100;
scoreDisplay.width = 20;
scoreDisplay.selectable = false;
var scoreDisplayFormat = new TextFormat();
scoreDisplayFormat.color = 0xFFFFFF;
scoreDisplayFormat.font = "Arial";
scoreDisplayFormat.align = "right";
scoreDisplayFormat.size = 15;
scoreDisplay.defaultTextFormat = scoreDisplayFormat;
scoreObjects.addChild(scoreDisplay);
updateScore();
}
// new score to show
public function updateScore() {
scoreDisplay.text = String(gameScore);
}
// remove a ship icon
public function removeShipIcon() {
scoreObjects.removeChild(shipIcons.pop());
}
// remove a shield icon
public function removeShieldIcon() {
scoreObjects.removeChild(shieldIcons.pop());
}
// remove the rest of the ship icons
public function removeAllShipIcons() {
while (shipIcons.length > 0) {
removeShipIcon();
}
}
// remove the rest of the shield icons
public function removeAllShieldIcons() {
while (shieldIcons.length > 0) {
removeShieldIcon();
}
}
// SHIP CREATION AND MOVEMENT
// create a new ship
public function newShip(event:TimerEvent) {
// if ship exists, remove it
if (ship != null) {
gameObjects.removeChild(ship);
ship = null;
}
// no more ships
if (shipsLeft < 1) {
endGame();
return;
}
// create, position, and add new ship
ship = new Ship();
ship.gotoAndStop(1);
ship.x = 400;
ship.y = 350;
ship.rotation = -180;
ship.shield.visible = false;
gameObjects.addChild(ship);
// set up ship properties
shipMoveX = 0.0;
shipMoveY = 0.0;
gameMode = "play";
// set up shields
shieldsLeft = 3;
createShieldIcons();
// all lives but the first start with a free shield
if (shipsLeft != startingShips) {
startShield(true);
}
}
// register key presses
public function keyDownFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
leftArrow = true;
} else if (event.keyCode == 40) {
rightArrow = true;
} else if (event.keyCode == 32) { // space
newMissile();
} else if (event.keyCode == 90) { // z
startShield(false);
}
}
// register key ups
public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
leftArrow = false;
} else if (event.keyCode == 40) {
rightArrow = false;
}
}
// animate ship
public function moveShip(timeDiff:uint) {
// rotate and thrust
if (leftArrow) {
ship.y -= 2;
} else if (rightArrow) {
ship.y+= 2;
}
// move
ship.x += shipMoveX;
ship.y += shipMoveY;
// check boundaries
if (ship.y < 65) ship.y = 65;
if (ship.y > 380) ship.y = 380;
}
// remove ship
public function shipHit() {
gameMode = "delay";
ship.gotoAndPlay("explode");
removeAllShieldIcons();
delayTimer = new Timer(2000,1);
delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE,newShip);
delayTimer.start();
removeShipIcon();
shipsLeft--;
}
// turn on shield for 3 seconds
public function startShield(freeShield:Boolean) {
if (shieldsLeft < 1) return; // no shields left
if (shieldOn) return; // shield already on
// turn on shield and set timer to turn off
ship.shield.visible = true;
shieldTimer = new Timer(3000,1);
shieldTimer.addEventListener(TimerEvent.TIMER_COMPLETE,endShield);
shieldTimer.start();
// update shields remaining
if (!freeShield) {
removeShieldIcon();
shieldsLeft--;
}
shieldOn = true;
}
// turn off shield
public function endShield(event:TimerEvent) {
ship.shield.visible = false;
shieldOn = false;
}
// ROCKS
// create a single rock of a specific size
public function newRock(x,y:int, rockType:String) {
// create appropriate new class
var newRock:MovieClip;
var rockRadius:Number;
if (rockType == "Big") {
newRock = new Rock_Big();
rockRadius = 35;
} else if (rockType == "Medium") {
newRock = new Rock_Medium();
rockRadius = 20;
} else if (rockType == "Small") {
newRock = new Rock_Small();
rockRadius = 10;
}
// choose a random look
newRock.gotoAndStop(Math.ceil(Math.random()*3+1));
// set start position
newRock.x = Math.random()*0;
newRock.y = Math.random()*280+80;
// set random movement and rotation
var dx:Number = Math.random()*3;
var dy:Number = Math.random()*2;
// add to stage and to rocks list
gameObjects.addChild(newRock);
rocks.push({rock:newRock, dx:dx, dy:dy, rockType:rockType, rockRadius: rockRadius});
}
// create four rocks
public function nextRockWave(event:TimerEvent) {
rocks = new Array();
newRock(100,1,"Big");
newRock(200,1,"Big");
newRock(450,1,"Big");
newRock(350,1,"Big");
gameMode = "play";
}
// animate all rocks
public function moveRocks(timeDiff:uint) {
for(var i:int=rocks.length-1;i>=0;i--) {
// move the rocks
var rockSpeed:Number = rockSpeedStart + rockSpeedIncrease*gameLevel;
rocks[i].rock.x += rocks[i].dx*timeDiff*rockSpeed;
rocks[i].rock.y += rocks[i].dy*rockSpeed;
// wrap rocks
if ((rocks[i].rock.x > 0) && (x <-50)) {
deleteRocks();
}
else if ((rocks[i].rock.x < 0) && (x > 50)) {
deleteRocks();
}
}
}
public function rockHit(rockNum:uint) {
// create two smaller rocks
if (rocks[rockNum].rockType == "Big") {
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Medium");
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Medium");
}
// remove original rock
gameObjects.removeChild(rocks[rockNum].rock);
rocks.splice(rockNum,1);
}
public function deleteRocks(){
gameMode = "delay";
newRock.gotoAndPlay("bang");
}
// MISSILES
// create a new Missile
public function newMissile() {
// create
var newMissile:Missile = new Missile();
// set direction
newMissile.dx = Math.cos(Math.PI*ship.rotation/180);
newMissile.dy = Math.sin(Math.PI*ship.rotation/180);
// placement
newMissile.x = ship.x + newMissile.dx*shipRadius;
newMissile.y = ship.y + newMissile.dy*shipRadius;
// add to stage and array
gameObjects.addChild(newMissile);
missiles.push(newMissile);
}
// animate missiles
public function moveMissiles(timeDiff:uint) {
for(var i:int=missiles.length-1;i>=0;i--) {
// move
missiles[i].x += missiles[i].dx*missileSpeed*timeDiff;
missiles[i].y += missiles[i].dy*missileSpeed*timeDiff;
// moved off screen
if ((missiles[i].x < 0) || (missiles[i].x > 550) || (missiles[i].y < 0) || (missiles[i].y > 400)) {
gameObjects.removeChild(missiles[i]);
delete missiles[i];
missiles.splice(i,1);
}
}
}
// remove a missile
public function missileHit(missileNum:uint) {
gameObjects.removeChild(missiles[missileNum]);
missiles.splice(missileNum,1);
}
// GAME INTERACTION AND CONTROL
public function moveGameObjects(event:Event) {
// get timer difference and animate
var timePassed:uint = getTimer() - lastTime;
lastTime += timePassed;
moveRocks(timePassed);
if (gameMode != "delay") {
moveShip(timePassed);
}
moveMissiles(timePassed);
checkCollisions();
}
// look for missiles colliding with rocks
public function checkCollisions() {
// loop through rocks
rockloop: for(var j:int=rocks.length-1;j>=0;j--) {
// loop through missiles
missileloop: for(var i:int=missiles.length-1;i>=0;i--) {
// collision detection
if (Point.distance(new Point(rocks[j].rock.x,rocks[j].rock.y),
new Point(missiles[i].x,missiles[i].y))
< rocks[j].rockRadius) {
// remove rock and missile
rockHit(j);
missileHit(i);
// add score
gameScore += 10;
updateScore();
// break out of this loop and continue next one
continue rockloop;
}
}
// check for rock hitting ship
if (gameMode == "play") {
if (shieldOn == false) { // only if shield is off
if (Point.distance(new Point(rocks[j].rock.x,rocks[j].rock.y),
new Point(ship.x,ship.y))
< rocks[j].rockRadius+shipRadius) {
// remove ship and rock
shipHit();
rockHit(j);
}
}
}
}
// all out of rocks, change game mode and trigger more
if ((rocks.length == 0) && (gameMode == "play")) {
gameMode = "betweenlevels";
gameLevel++; // advance a level
delayTimer = new Timer(2000,1);
delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE,nextRockWave);
delayTimer.start();
}
}
public function endGame() {
// remove all objects and listeners
removeChild(gameObjects);
removeChild(scoreObjects);
gameObjects = null;
scoreObjects = null;
removeEventListener(Event.ENTER_FRAME,moveGameObjects);
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
gotoAndStop("gameover");
}
}
}
thanks in advance for the help!!
first pass out the rock you want to delete
deleteRocks(rocks[i].rock);
then remove it from the stage
public function deleteRocks(rock){
gameMode = "delay";
trace("Rock Deleted");
gameObjects.removeChild(rock) ;
}
But I think there is a problem with your if condition that control the removing of rocks. check it out

Errors on end game on score

OK I"ve managed to fix most of the error, the main remaining ones are when I try to make the game end when it hits 50... This is now the error I get and when I go into the next level the ship disappears, but the game plays with an invisible ship....
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at SpaceRocks_v008/newShip()[/Users/Jess/Documents/UNI/INFT6303_game_design/Ass_3/Flash_V2/SpaceRocks_v008.as:168]
at SpaceRocks_v008/startSpaceRocks_v008()[/Users/Jess/Documents/UNI/INFT6303_game_design/Ass_3/Flash_V2/SpaceRocks_v008.as:84]
at SpaceRocks_v008/frame2()
Cannot display source code at this location.
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.geom.Point;
public class SpaceRocks_v008 extends MovieClip {
static const shipRotationSpeed:Number = .1;
static const rockSpeedStart:Number = .03;
static const rockSpeedIncrease:Number = .02;
static const missileSpeed:Number = .2;
static const thrustPower:Number = .15;
static const shipRadius:Number = 20;
static const startingShips:uint = 3;
// game objects
private var ship:Ship;
private var rocks:Array;
private var missiles:Array;
// animation timer
private var lastTime:uint;
// arrow keys
private var rightArrow:Boolean = false;
private var leftArrow:Boolean = false;
private var upArrow:Boolean = false;
// ship velocity
private var shipMoveX:Number;
private var shipMoveY:Number;
// timers
private var delayTimer:Timer;
private var shieldTimer:Timer;
// game mode
private var gameMode:String;
private var shieldOn:Boolean;
// ships and shields
private var shipsLeft:uint;
private var shieldsLeft:uint;
private var shipIcons:Array;
private var shieldIcons:Array;
private var scoreDisplay:TextField;
// score and level
private var gameScore1:Number;
private var gameLevel:uint;
// sprites
private var gameObjects:Sprite;
private var scoreObjects:Sprite;
// start the game
public function startSpaceRocks_v008() {
// set up sprites
gameObjects = new Sprite();
addChild(gameObjects);
scoreObjects = new Sprite();
addChild(scoreObjects);
// reset score objects
gameLevel = 1;
shipsLeft = startingShips;
gameScore1 = 0;
createShipIcons();
createScoreDisplay();
// set up listeners
addEventListener(Event.ENTER_FRAME,moveGameObjects);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
// start
gameMode = "delay";
shieldOn = false;
missiles = new Array();
nextRockWave(null);
newShip(null);
}
// SCORE OBJECTS
// draw number of ships left
public function createShipIcons() {
shipIcons = new Array();
for(var i:uint=0;i<shipsLeft;i++) {
var newShip:ShipIcon = new ShipIcon();
newShip.x = 460+i*30;
newShip.y = 328;
scoreObjects.addChild(newShip);
shipIcons.push(newShip);
}
}
// draw number of shields left
public function createShieldIcons() {
shieldIcons = new Array();
for(var i:uint=0;i<shieldsLeft;i++) {
var newShield:ShieldIcon = new ShieldIcon();
newShield.x = 520-i*30;
newShield.y = 210;
scoreObjects.addChild(newShield);
shieldIcons.push(newShield);
}
}
// put the numerical score at the upper right
public function createScoreDisplay() {
scoreDisplay = new TextField();
scoreDisplay.x = 460;
scoreDisplay.y = 68;
scoreDisplay.width = 40;
scoreDisplay.selectable = false;
var scoreDisplayFormat = new TextFormat();
scoreDisplayFormat.color = 0xFFFFFF;
scoreDisplayFormat.font = "Arial";
scoreDisplayFormat.align = "right";
scoreDisplayFormat.size = 15;
scoreDisplay.defaultTextFormat = scoreDisplayFormat;
scoreObjects.addChild(scoreDisplay);
updateScore();
}
// new score to show
public function updateScore() {
scoreDisplay.text = String(gameScore1);
}
// remove a ship icon
public function removeShipIcon() {
scoreObjects.removeChild(shipIcons.pop());
}
// remove a shield icon
public function removeShieldIcon() {
scoreObjects.removeChild(shieldIcons.pop());
}
// remove the rest of the ship icons
public function removeAllShipIcons() {
while (shipIcons.length > 0) {
removeShipIcon();
}
}
// remove the rest of the shield icons
public function removeAllShieldIcons() {
while (shieldIcons.length > 0) {
removeShieldIcon();
}
}
// SHIP CREATION AND MOVEMENT
// create a new ship
public function newShip(event:TimerEvent) {
// if ship exists, remove it
if (ship != null) {
gameObjects.removeChild(ship);
ship = null;
}
// no more ships
if (shipsLeft < 1) {
endGame();
return;
}
//upper scrore reached
if (gameScore1 >= 50) {
trace("high")
endGame();
return;
}
// create, position, and add new ship
ship = new Ship();
ship.gotoAndStop(1);
ship.x = 400;
ship.y = 350;
ship.rotation = -180;
ship.shield.visible = false;
gameObjects.addChild(ship);
// set up ship properties
shipMoveX = 0.0;
shipMoveY = 0.0;
gameMode = "play";
// set up shields
shieldsLeft = 3;
createShieldIcons();
// all lives but the first start with a free shield
if (shipsLeft != startingShips) {
startShield(true);
}
}
// register key presses
public function keyDownFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
leftArrow = true;
} else if (event.keyCode == 40) {
rightArrow = true;
} else if (event.keyCode == 32) { // space
newMissile();
} else if (event.keyCode == 37) { // left arrow
startShield(false);
}
}
// register key ups
public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
leftArrow = false;
} else if (event.keyCode == 40) {
rightArrow = false;
}
}
// animate ship
public function moveShip(timeDiff:uint) {
// rotate and thrust
// rotate and thrust
if (leftArrow) {
ship.y -= 2;
} else if (rightArrow) {
ship.y+= 2;
}
// move
ship.x += shipMoveX;
ship.y += shipMoveY;
// wrap around screen
if (ship.y < 65) ship.y = 65;
if (ship.y > 380) ship.y = 380;
}
// remove ship
public function shipHit() {
gameMode = "delay";
ship.gotoAndPlay("explode");
removeAllShieldIcons();
delayTimer = new Timer(1000,1);
delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE,newShip);
delayTimer.start();
removeShipIcon();
shipsLeft--;
}
// turn on shield for 3 seconds
public function startShield(freeShield:Boolean) {
if (shieldsLeft < 1) return; // no shields left
if (shieldOn) return; // shield already on
// turn on shield and set timer to turn off
ship.shield.visible = true;
shieldTimer = new Timer(3000,1);
shieldTimer.addEventListener(TimerEvent.TIMER_COMPLETE,endShield);
shieldTimer.start();
// update shields remaining
if (!freeShield) {
removeShieldIcon();
shieldsLeft--;
}
shieldOn = true;
}
// turn off shield
public function endShield(event:TimerEvent) {
ship.shield.visible = false;
shieldOn = false;
}
// ROCKS
// create a single rock of a specific size
public function newRock(x,y:int, rockType:String) {
// create appropriate new class
var newRock:MovieClip;
var rockRadius:Number;
if (rockType == "Big") {
newRock = new Rock_Big();
rockRadius = 35;
} else if (rockType == "Medium") {
newRock = new Rock_Medium();
rockRadius = 30;
} else if (rockType == "Small") {
newRock = new Rock_Small();
rockRadius = 25;
}
// choose a random look
newRock.gotoAndStop(Math.ceil(Math.random()*3));
// set start position
newRock.x = Math.random()*0;
newRock.y = Math.random()*280+80;
// set random movement and rotation
var dx:Number = Math.random()*3;
var dy:Number = Math.random()*2;
// add to stage and to rocks list
gameObjects.addChild(newRock);
rocks.push({rock:newRock, dx:dx, dy:dy, rockType:rockType, rockRadius: rockRadius});
}
// create four rocks
public function nextRockWave(event:TimerEvent) {
rocks = new Array();
newRock(100,1,"Big");
newRock(200,1,"Big");
newRock(450,1,"Big");
newRock(350,1,"Big");
gameMode = "play";
}
// animate all rocks
public function moveRocks(timeDiff:uint) {
for(var i:int=rocks.length-1;i>=0;i--) {
// move the rocks
var rockSpeed:Number = rockSpeedStart + rockSpeedIncrease*gameLevel;
rocks[i].rock.x += rocks[i].dx*timeDiff*rockSpeed;
rocks[i].rock.y += 0
// wrap rocks
if ((rocks[i].rock.x) > 400){
deleteRocks(i);
}
else if ((rocks[i].rock.y) > 401){
deleteRocks(i);
}
}
}
public function rockHit(rockNum:uint) {
// create two smaller rocks
if (rocks[rockNum].rockType == "Big") {
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Medium");
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Medium");
} else if (rocks[rockNum].rockType == "Medium") {
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Small");
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Small");
}
// remove original rock
rocks[rockNum].rock.gotoAndPlay("bang");
//gameObjects.removeChild(rocks[rockNum].rock);
rocks.splice(rockNum,1);
}
public function deleteRocks(rockNum:uint) {
//remove rock from game
gameObjects.removeChild(rocks[rockNum].rock);
rocks.splice(rockNum,1);
}
// MISSILES
// create a new Missile
public function newMissile() {
// create
var newMissile:Missile = new Missile();
// set direction
newMissile.dx = Math.cos(Math.PI*ship.rotation/180);
newMissile.dy = Math.sin(Math.PI*ship.rotation/180);
// placement
newMissile.x = ship.x + newMissile.dx*shipRadius;
newMissile.y = ship.y + newMissile.dy*shipRadius;
// add to stage and array
gameObjects.addChild(newMissile);
missiles.push(newMissile);
}
// animate missiles
public function moveMissiles(timeDiff:uint) {
for(var i:int=missiles.length-1;i>=0;i--) {
// move
missiles[i].x += missiles[i].dx*missileSpeed*timeDiff;
missiles[i].y += missiles[i].dy*missileSpeed*timeDiff;
// moved off screen
if ((missiles[i].x < 0) || (missiles[i].x > 550) || (missiles[i].y < 0) || (missiles[i].y > 400)) {
gameObjects.removeChild(missiles[i]);
delete missiles[i];
missiles.splice(i,1);
}
}
}
// remove a missile
public function missileHit(missileNum:uint) {
gameObjects.removeChild(missiles[missileNum]);
missiles.splice(missileNum,1);
}
// GAME INTERACTION AND CONTROL
public function moveGameObjects(event:Event) {
// get timer difference and animate
var timePassed:uint = getTimer() - lastTime;
lastTime += timePassed;
moveRocks(timePassed);
if (gameMode != "delay") {
moveShip(timePassed);
}
moveMissiles(timePassed);
checkCollisions();
}
// look for missiles colliding with rocks
public function checkCollisions() {
// loop through rocks
rockloop: for(var j:int=rocks.length-1;j>=0;j--) {
// loop through missiles
missileloop: for(var i:int=missiles.length-1;i>=0;i--) {
// collision detection
if (Point.distance(new Point(rocks[j].rock.x,rocks[j].rock.y),
new Point(missiles[i].x,missiles[i].y))
< rocks[j].rockRadius) {
// remove rock and missile
rockHit(j);
missileHit(i);
// add score
gameScore1 += 10;
updateScore();
// break out of this loop and continue next one
continue rockloop;
}
}
// check for rock hitting ship
if (gameMode == "play") {
if (shieldOn == false) { // only if shield is off
if (Point.distance(new Point(rocks[j].rock.x,rocks[j].rock.y),
new Point(ship.x,ship.y))
< rocks[j].rockRadius+shipRadius) {
// remove ship and rock
shipHit();
rockHit(j);
}
}
}
}
if (gameScore1 >= 50) {
shipsLeft = 0;
if (shipsLeft < 1) {
endGame();
return;
}
}
// all out of rocks, change game mode and trigger more
if ((rocks.length == 0) && (gameMode == "play")) {
gameMode = "betweenlevels";
gameLevel++; // advance a level
delayTimer = new Timer(2000,1);
delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE,nextRockWave);
delayTimer.start();
}
}
public function endGame() {
// remove all objects and listeners
removeChild(gameObjects);
removeChild(scoreObjects);
gameObjects = null;
scoreObjects = null;
removeEventListener(Event.ENTER_FRAME,moveGameObjects);
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
gotoAndStop("gameover");
}
}
}

Error #1034: Type Coercion failed: cannot convert flash.display::Stage#27dfe089 to flash.display.MovieClip

here it is the error >> TypeError: Error #1034: Type Coercion failed: cannot convert flash.display::Stage#261b4089 to flash.display.MovieClip.
at com.ply::Heli/fireBullet()
at com.ply::Heli/myOnPress()
this is Heli's Class :
package com.ply
{
import flash.display.MovieClip;
import flash.display.*;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import com.peluru.Bullet;
public class Heli extends MovieClip
{
var shotCooldown:int;
const MAX_COOLDOWN = 10;
//Settings
public var xAcceleration:Number = 0;
public var yAcceleration:Number = 0;
private var xSpeed:Number = 0;
private var ySpeed:Number = 0;
private var up:Boolean = false;
private var down:Boolean = false;
private var left:Boolean = false;
private var right:Boolean = false;
public function Heli()
{
shotCooldown = MAX_COOLDOWN;
bullets = new Array();
addEventListener(Event.ENTER_FRAME, update);
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
init();
}
public function onAddedToStage(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.addEventListener(KeyboardEvent.KEY_DOWN, myOnPress);
stage.addEventListener(KeyboardEvent.KEY_UP, myOnRelease);
init();
}
private function init():void
{
addEventListener(Event.ENTER_FRAME, RunHeli);
}
private function RunHeli(event:Event):void
{
xSpeed += xAcceleration ; //increase the speed by the acceleration
ySpeed += yAcceleration ; //increase the speed by the acceleration
xSpeed *= 0.95; //apply friction
ySpeed *= 0.95; //so the speed lowers after time
if(Math.abs(xSpeed) < 0.02) //if the speed is really low
{
xSpeed = 0; //set it to 0
//Otherwise I'd go very small but never really 0
}
if(Math.abs(ySpeed) < 0.02) //same for the y speed
{
ySpeed = 0;
}
xSpeed = Math.max(Math.min(xSpeed, 10), -10); //dont let the speed get bigger as 10
ySpeed = Math.max(Math.min(ySpeed, 10), -10); //and dont let it get lower than -10
this.x += xSpeed; //increase the position by the speed
this.y += ySpeed; //idem
}
public function update(e:Event){
shotCooldown-- ;
}
/**
* Keyboard Handlers
*/
public function myOnPress(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT)
{
xAcceleration = -1;
}
else if(event.keyCode == Keyboard.RIGHT)
{
xAcceleration = 1;
}
else if(event.keyCode == Keyboard.UP)
{
yAcceleration = -1;
}
else if(event.keyCode == Keyboard.DOWN)
{
yAcceleration = 1;
}
else if (event.keyCode == 32)
{
fireBullet();
}
}
public function myOnRelease(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
xAcceleration = 0;
}
else if(event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
yAcceleration = 0;
}
}
public function fireBullet() {
if (shotCooldown <=0 )
{
shotCooldown=MAX_COOLDOWN;
var b = new Bullet();
var b2= new Bullet();
b.x = this.x +20;
b.y = this.y ;
b2.x= this.x -20;
b2.y= this.y ;
MovieClip(parent).bullets.push(b);
MovieClip(parent).bullets.push(b2);
trace(bullets.length);
parent.addChild(b);
parent.addChild(b2);
}
}
}
}
and this is the Main Class
package
{
import com.ply.Heli;
import com.peluru.Bullet;
import com.musuh.Airplane2;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.*;
import flash.events.*;
import flash.utils.*;
public class Main extends MovieClip
{
public static const STATE_INIT:int = 10;
public static const STATE_START_PLAYER:int = 20;
public static const STATE_PLAY_GAME:int = 30;
public static const STATE_REMOVE_PLAYER:int = 40;
public static const STATE_END_GAME:int = 50;
public var gameState:int = 0;
public var player:Heli;
public var enemy:Airplane2;
//public var bulletholder:MovieClip = new MovieClip();
//================================================
public var cTime:int = 1;
//the time it has to reach in order to be allowed to shoot (in frames)
public var cLimit:int = 10;
//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 = 64;
//the player's score
public var score:int = 0;
public var gameOver:Boolean = false;
public var bulletContainer:MovieClip = new MovieClip();
//================================================
private var nextPlane:Timer;
public var enemies:Array;
public var bullets:Array;
public function Main()
{
gameState = STATE_INIT;
gameLoop();
}
public function gameLoop(): void {
switch(gameState) {
case STATE_INIT :
initGame();
break
case STATE_START_PLAYER:
startPlayer();
break;
case STATE_PLAY_GAME:
playGame();
break;
case STATE_REMOVE_PLAYER:
//removePlayer();
break;
case STATE_END_GAME:
break;
}
}
public function initGame() :void {
enemies = new Array();
bullets = ne Array();
setNextPlane();
gameState = STATE_START_PLAYER;
gameLoop();
//stage.addEventListener(Event.ENTER_FRAME, AddEnemy);
stage.addEventListener(Event.ENTER_FRAME, back);
stage.addEventListener(Event.ENTER_FRAME,checkForHits);
}
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
// create plane
var enemy:Airplane2 = new Airplane2();
enemy.y = -1 * enemy.height;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
enemy.x = Math.floor(Math.random()*(stage.stageWidth - enemy.width));
//then add the enemy to stage
addChild(enemy);
enemies.push(enemy);
// set time for next plane
setNextPlane();
}
public function removePlane(plane:Airplane2) {
for(var i in enemies) {
if (enemies[i] == plane) {
enemies.splice(i,1);
break;
}
}
}
// take a bullet from the array
public function removeBullet(bullet:Bullet) {
for(var i in bullets) {
if (bullets[i] == bullet) {
bullets.splice(i,1);
break;
}
}
}
public function checkForHits(event:Event) {
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var airplaneNum:int=enemies.length-1;airplaneNum>=0;airplaneNum--) {
if (bullets[bulletNum].hitTestObject(enemies[airplaneNum])) {
enemies[airplaneNum].planeHit();
bullets[bulletNum].deleteBullet();
trace("kena");
//shotsHit++;
//showGameScore();
break;
}
}
}
//if ((shotsLeft == 0) && (bullets.length == 0)) {
// endGame();
//}
}
public function back( evt:Event ):void
{ // Backgroud Land
if (Dessert2.y >= 0 && Dessert.y >= 720)
{
Dessert.y = Dessert2.y - 1240 ;
}
else if (Dessert.y >= 0 && Dessert2.y >= 720)
{
Dessert2.y = Dessert.y - 1240 ;
}
else
{
Dessert.y = Dessert.y +5 ;
Dessert2.y = Dessert2.y +5 ;
}
// Background Clouds
if (Clouds2.y >= 0 && Clouds.y >= 720)
{
Clouds.y = Clouds2.y - 2480 ;
}
else if (Clouds.y >= 0 && Clouds2.y >= 720)
{
Clouds2.y = Clouds.y - 2480 ;
}
else
{
Clouds.y = Clouds.y +10 ;
Clouds2.y = Clouds2.y +10 ;
}
}
public function startPlayer() : void {
player=new Heli();
player.x = stage.stageWidth / 2;
player.y = stage.stageHeight / 2;
// add Player to display list
stage.addChild(player);
gameState = STATE_PLAY_GAME;
}
public function playGame():void {
gameLoop();
//txtScore.text = 'Score: '+score;
}
function AddEnemy(event:Event){
if(enemyTime < enemyLimit){
enemyTime ++;
} else {
//defining a variable which will hold the new enemy
enemy =new Airplane2();
//making the enemy offstage when it is created
enemy.y = -1 * enemy.height;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
enemy.x = Math.floor(Math.random()*(stage.stageWidth - enemy.width));
//then add the enemy to stage
addChild(enemy);
//and reset the enemyTime
enemyTime = 0;
}
if(cTime <= cLimit){
cTime ++;
} else {
//if it has, then allow the user to shoot
shootAllow = true;
//and reset cTime
cTime = 1;
}
}
}
}
You have added your player in Main into stage instead of this - why, by the way? So, there are two methods of fixing this: First, change line where you add player to display list, and second, remove direct coercion from Heli.fireBullet() function. I'd say use the first one.
public function startPlayer() : void {
player=new Heli();
player.x = stage.stageWidth / 2;
player.y = stage.stageHeight / 2;
// add Player to display list
this.addChild(player); // <-- this, not stage
gameState = STATE_PLAY_GAME;
}
Change
MovieClip(parent).bullets.push(b);
MovieClip(parent).bullets.push(b2);
to
MovieClip(root).bullets.push(b);
MovieClip(root).bullets.push(b2);

AS3 Generating differnet Enemies and bullets hitTest Problems

I'm creating a 2d side scrolling shooter with 4 different types of Enemies and 3 different types of bullets. I'm using a factory class to create the enemies and a for loop inside a for loop to do hit testing. When I run my code for some reason when one enemy get's hit some of my other enemies die. Could someone please help me locate and fix my problem.
Here's one of the Enemy classes. The other 3 are identical except with different var values.
package char {
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
public class Enemy1 extends MovieClip {
private var _type:String;
private var _health:Number;
private var _vx:Number;
private var _vy:Number;
private var _stage:Stage;
private static var _instance:Enemy1;
public function Enemy1() {
init();
}
private function init():void {
//Vars
_vx = -5;
_vy = Math.random()*5;
_health = 1;
_stage = Main.getStage();
_instance = this;
//Listeners
addEventListener(Event.ADDED_TO_STAGE, onAdded);
addEventListener(Event.ENTER_FRAME, enemyLoop);
addEventListener(Event.REMOVED_FROM_STAGE, onRemoved);
}
//When Added
private function onAdded(event:Event):void{
//Set position
this.x = _stage.stageWidth;
this.y = Math.random() * _stage.stageHeight;
//trace("Enemy created");
dispatchEvent(new Event("enemyCreated", true));
}
//Loop
private function enemyLoop(event:Event):void {
//Move
x += _vx;
y += _vy;
//Boundaries
if ( this.y <= 0 + this.height/2){
this.y = this.height/2;
_vy *= -1;
}
if ( this.y >= _stage.stageHeight - this.width/2){
this.y = _stage.stageHeight - this.width/2;
_vy *= -1;
}
//Health cheack
if ( _health <= 0){
if (this.parent) {
this.parent.removeChild(this);
Main.setScore(10);
}
}
//Leaves screen
if (this.x <= -this.width){
if (this.parent) {
this.parent.removeChild(this);
}
}
}
public function isHit(type:String):void{
//trace(this + " is hit by " + type);
if(type == "power"){
_health -= 1;
trace(_health);
}
else if(type == "quick"){
_health -= 1;
trace(_health);
}
else if(type == "strong"){
_health -= 1;
trace(_health);
}
}
public function getHealth():Number{
return _health;
}
public function getEnemy1():Enemy1{
return _instance;
}
//When Removed
private function onRemoved(event:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, onAdded);
removeEventListener(Event.ENTER_FRAME, enemyLoop);
removeEventListener(Event.REMOVED_FROM_STAGE, onRemoved);
//trace("enemy removed");
}
}
}
And here's my main class that checks for all the hitTests
package screen {
import flash.display.MovieClip;
import flash.events.Event;
import com.greensock.TweenLite;
import com.greensock.easing.*;
import char.Player;
import char.EnemyFactory;
public class Level1 extends MovieClip {
//Consts
private const ENEMY_CHANCE:Number = 0.025;
//Vars
private var _player:Player;
private var _enemyBudget:Number = 20;
private static var _bullets:Array = [];
private static var _enemies:Array = [];
public function Level1() {
init();
}
private function init():void {
//Vars
this.alpha = 0;
_enemyBudget = 20;
//Event listeners
addEventListener(Event.ENTER_FRAME, levelLoop);
addEventListener(Event.ADDED_TO_STAGE, onAdded);
addEventListener(Event.REMOVED_FROM_STAGE, onRemoved);
//Add This
Main.getInstance().addChild(this);
}
private function onAdded(event:Event):void {
TweenLite.to(this, 0.5, {alpha:1});
_player = new Player();
trace("Level 1 reaady");
}
private function levelLoop(event:Event):void{
//Health bar
_healthBar.scaleX = Main.getPlayerHealth() / 100;
//enemy creation
if(_enemyBudget <= 20 && _enemyBudget > 10){
if (ENEMY_CHANCE > Math.random()){
var randomEnemy:Number = Math.random()* 1.2;
//trace(randomEnemy);
if(randomEnemy <= 0.5){
//trace("Enemy 1");
var enemy1:MovieClip = char.EnemyFactory.makeEnemy("weak");
Main.getInstance().addChild(enemy1);
_enemyBudget -= 1;
}
else if(randomEnemy > 0.5 && randomEnemy <= 0.8){
//trace("Enemy 2");
var enemy2:MovieClip = char.EnemyFactory.makeEnemy("quick");
Main.getInstance().addChild(enemy2);
_enemyBudget -= 3;
}
else if(randomEnemy > 0.8 && randomEnemy <= 1){
//trace("Enemy 3");
var enemy3:MovieClip = char.EnemyFactory.makeEnemy("strong");
Main.getInstance().addChild(enemy3);
_enemyBudget -= 3;
}
else if(randomEnemy > 1 && randomEnemy <= 1.2){
//trace("Enemy 4");
var enemy4:MovieClip = char.EnemyFactory.makeEnemy("power");
Main.getInstance().addChild(enemy4);
_enemyBudget -= 4;
}
}
}
else if(_enemyBudget <= 10 && _enemyBudget > 0){
if (ENEMY_CHANCE > Math.random()){
var randomEnemy:Number = Math.random();
if(randomEnemy <= 0.5){
//trace("Enemy 1");
var enemy1:MovieClip = char.EnemyFactory.makeEnemy("weak");
Main.getInstance().addChild(enemy1);
_enemyBudget -= 1;
}
else if(randomEnemy > 0.5 && randomEnemy <= 0.8){
//trace("Enemy 2");
var enemy2:MovieClip = char.EnemyFactory.makeEnemy("quick");
Main.getInstance().addChild(enemy2);
_enemyBudget -= 3;
}
else if(randomEnemy > 0.8 && randomEnemy <= 1){
//trace("Enemy 3");
var enemy3:MovieClip = char.EnemyFactory.makeEnemy("strong");
Main.getInstance().addChild(enemy3);
_enemyBudget -= 3;
}
}
}
else if(_enemyBudget <= 0){
if(_enemies == []){
trace("Game End");
}
}
if( Main.getPlayerHealth() <= 0){
trace("Player Dead. End Game");
}
for (var i:int = 0; i < _enemies.length; i++){
for(var j:int = 0; j < _bullets.length; j++){
if(_bullets[j] != null && _enemies[i] != null){
//Check if bullet hits enemy
if(_bullets[j].hitTestObject(_enemies[i])){
//removes bullet
if (_bullets[j].parent) {
_bullets[j].parent.removeChild(_bullets[j]);
}
//Tells enemy he's hit
if(_enemies[i] != null){
_enemies[i].isHit(_bullets[j].getType());
}
//Checks enemy health
if(_enemies[i].getHealth() <= 0){
if(_enemies[i] == null){
_enemies.splice(i, 1);
i--;
}
}
//Removes bullet from array
if(_bullets[j] == null){
_bullets.splice(j, 1);
j--;
}
}
//Check if player hit
if(_enemies[i] != null && _player != null){
if(_enemies[i].hitTestObject(_player)){
if (_enemies[i].parent) {
_enemies[i].parent.removeChild(_enemies[i]);
Main.setPlayerHealth(-10);
}
}
if(_enemies[i] == null){
_enemies.splice(i, 1);
i--;
}
}
}
}
}
}
private function onRemoved(event:Event):void{
removeEventListener(Event.ENTER_FRAME, levelLoop);
removeEventListener(Event.ADDED_TO_STAGE, onAdded);
removeEventListener(Event.REMOVED_FROM_STAGE, onRemoved);
}
//Get instance
public static function addBullet(bullet:MovieClip):void {
_bullets.push(MovieClip(bullet));
}
public static function addEnemy(enemy:MovieClip):void{
_enemies.push(MovieClip(enemy));
//trace(enemy + " was added to enemy array.");
}
}
}
And here's the function inside the Bullet class that return's it's type.
public function getType():String{
return TYPE;
}
It's hard to say with certainty, this would be easy to confirm by stepping through the code in a debugger.
But what looks suspicious to me is that you're iterating over arrays of enemies/bullets, and in the middle of doing that, you delete elements from the array and decrement the counter variables. Generally, when you need to iterate over something and potentially remove elements from the thing you're iterating over, you should do that iteration in a backwards fashion. That way changing the length and contents of the array in the middle of the loop is harmless.
for (var i:int = enemeies.length -1; i >= 0; i--)
{
// do your stuff and remove elements from the
// enemies array at will ... just splice the current
// element at index i out here, don't decrement i as
// you've done in your code above it will get decremented
// by the for loop
}

AS3 - Game Timer not calculating start time properly

I'm building a game in AS3 based off of Gary Rosenzweig's latest Actionscript 3 book. It has a game timer issue, not just mine but his demo too, that I can't figure out.
The game is like Asteroids where four rocks are placed in the corners of the stage at the beginning and then start moving randomly around the stage. The problem is the timer used is started the moment that the flash file starts not the moment the player clicks the start button. So if you are on the start screen for 5 seconds before you click play when the game actually begins the rocks are where they would be after 5 seconds of play, which could be right over the player.
I've posted the parts of the code that I think apply. Could someone please tell me how to modify this so that when the player actually starts the game the rocks start in their proper places. I'm pretty sure it's the last function that I've included that is the problem but I've included other related parts to give you a more complete picture.
package {
import flash.display.*;
import flash.events.*;
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.text.*;
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.geom.Point;
import flash.net.SharedObject;
import flash.media.Sound;
import flash.media.SoundMixer;
import flash.media.SoundTransform;
import flash.media.SoundChannel;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
public class VirusDefender extends MovieClip {
static const shipRotationSpeed:Number = .1;
static const rockSpeedStart:Number = .03;
static const rockSpeedIncrease:Number = .01;
static const missileSpeed:Number = .2;
static const thrustPower:Number = .15;
static const shipRadius:Number = 20;
static const startingShips:uint = 3;
// game objects
private var ship:Ship;
private var rocks:Array;
private var missiles:Array;
// animation timer
private var lastTime:uint;
// arrow keys
private var rightArrow:Boolean = false;
private var leftArrow:Boolean = false;
private var upArrow:Boolean = false;
// ship velocity
private var shipMoveX:Number;
private var shipMoveY:Number;
// timers
private var delayTimer:Timer;
private var shieldTimer:Timer;
// game mode
private var gameMode:String;
private var shieldOn:Boolean;
// ships and shields
private var shipsLeft:uint;
private var shieldsLeft:uint;
private var shipIcons:Array;
private var shieldIcons:Array;
private var scoreDisplay:TextField;
// score and level
private var gameScore:Number;
private var gameLevel:uint;
// sprites
private var gameObjects:Sprite;
private var scoreObjects:Sprite;
var gameBackground:GameBackground = new GameBackground();
// sounds
var sndFire:fire_sound;
var sndFireChannel:SoundChannel;
var sndThruster:thruster_sound;
var sndThrusterChannel:SoundChannel;
var sndShield:shield_sound;
var sndShieldChannel:SoundChannel;
var sndExplosion:explosion_sound;
var sndExplosionChannel:SoundChannel;
var sndBubble:bubble_sound;
var sndBubbleChannel:SoundChannel;
// start the game
public function startSpaceRocks() {
// set up sprites
addChild(gameBackground);
setChildIndex(gameBackground,0); // I added this
gameObjects = new Sprite();
addChild(gameObjects);
scoreObjects = new Sprite();
addChild(scoreObjects);
// reset score objects
gameLevel = 1;
shipsLeft = startingShips;
gameScore = 0;
createShipIcons();
createScoreDisplay();
// set up listeners
trace("add moveGameObjects event listener");
addEventListener(Event.ENTER_FRAME,moveGameObjects);
leftButton.addEventListener(TouchEvent.TOUCH_OVER,leftPress);
leftButton.addEventListener(TouchEvent.TOUCH_OUT,leftRelease);
rightButton.addEventListener(TouchEvent.TOUCH_OVER,rightPress);
rightButton.addEventListener(TouchEvent.TOUCH_OUT,rightRelease);
thrusterButton.addEventListener(TouchEvent.TOUCH_OVER,thrusterPress);
thrusterButton.addEventListener(TouchEvent.TOUCH_OUT,thrusterRelease);
shieldButton.addEventListener(TouchEvent.TOUCH_OVER,shieldPress);
fireButton.addEventListener(TouchEvent.TOUCH_OVER,firePress);
// Left Button
function leftPress(event:TouchEvent):void{
leftArrow = true;
}
function leftRelease(event:TouchEvent):void{
leftArrow = false;
}
// Right button
function rightPress(event:TouchEvent):void{
rightArrow = true;
}
function rightRelease(event:TouchEvent):void{
rightArrow = false;
}
// Thruster button
function thrusterPress(event:TouchEvent):void{
sndThruster=new thruster_sound();
sndThrusterChannel=sndThruster.play();
upArrow = true;
if (gameMode == "play") ship.gotoAndStop(2);
}
function thrusterRelease(event:TouchEvent):void{
sndThrusterChannel.stop();
upArrow = false;
if (gameMode == "play") ship.gotoAndStop(1);
}
// Fire button
function firePress(event:TouchEvent):void{
sndFire=new fire_sound();
sndFireChannel=sndFire.play();
newMissile();
}
// Shield button
function shieldPress(event:TouchEvent):void{
startShield(false);
}
// start
gameMode = "delay";
trace("gameMode - delay");
shieldOn = false;
missiles = new Array();
trace("nextRockWave fired");
nextRockWave(null);
newShip(null);
}
// SCORE OBJECTS
// draw number of ships left
public function createShipIcons() {
shipIcons = new Array();
for(var i:uint=0;i<shipsLeft;i++) {
var newShip:ShipIcon = new ShipIcon();
newShip.x = 165+i*25; //165
newShip.y = 273; //273
scoreObjects.addChild(newShip);
shipIcons.push(newShip);
}
}
// draw number of shields left
public function createShieldIcons() {
shieldIcons = new Array();
for(var i:uint=0;i<shieldsLeft;i++) {
var newShield:ShieldIcon = new ShieldIcon();
newShield.x = 310-i*25; //530
newShield.y = 273; //15
scoreObjects.addChild(newShield);
shieldIcons.push(newShield);
}
}
// put the numerical score at the upper right
public function createScoreDisplay() {
updateScore();
}
// new score to show
public function updateScore() {
score.text = addCommaInNumber(gameScore);
}
// remove a ship icon
public function removeShipIcon() {
scoreObjects.removeChild(shipIcons.pop());
}
// remove a shield icon
public function removeShieldIcon() {
scoreObjects.removeChild(shieldIcons.pop());
}
// remove the rest of the ship icons
public function removeAllShipIcons() {
while (shipIcons.length > 0) {
removeShipIcon();
}
}
// remove the rest of the shield icons
public function removeAllShieldIcons() {
while (shieldIcons.length > 0) {
removeShieldIcon();
}
}
// SHIP CREATION AND MOVEMENT
// create a new ship
public function newShip(event:TimerEvent) {
// if ship exists, remove it
if (ship != null) {
gameObjects.removeChild(ship);
ship = null;
}
// no more ships
if (shipsLeft < 1) {
endGame();
return;
}
// create, position, and add new ship
ship = new Ship();
ship.gotoAndStop(1);
ship.x = 240; //275
ship.y = 160; //200
ship.rotation = -90;
ship.shield.visible = false;
gameObjects.addChild(ship);
// set up ship properties
shipMoveX = 0.0;
shipMoveY = 0.0;
gameMode = "play";
// set up shields
shieldsLeft = 3;
createShieldIcons();
// all lives but the first start with a free shield
if (shipsLeft != startingShips) {
startShield(true);
sndShield=new shield_sound();
sndShieldChannel=sndShield.play();
}
}
// animate ship
public function moveShip(timeDiff:uint) {
// rotate and thrust
if (leftArrow) {
ship.rotation -= shipRotationSpeed*timeDiff;
} else if (rightArrow) {
ship.rotation += shipRotationSpeed*timeDiff;
} else if (upArrow) {
shipMoveX += Math.cos(Math.PI*ship.rotation/180)*thrustPower;
shipMoveY += Math.sin(Math.PI*ship.rotation/180)*thrustPower;
}
// move
ship.x += shipMoveX;
ship.y += shipMoveY;
// wrap around screen
if ((shipMoveX > 0) && (ship.x > 470)) {
ship.x -= 490;
}
if ((shipMoveX < 0) && (ship.x < -20)) {
ship.x += 500;
}
if ((shipMoveY > 0) && (ship.y > 320)) {
ship.y -= 340;
}
if ((shipMoveY < 0) && (ship.y < -20)) {
ship.y += 340;
}
}
// remove ship
public function shipHit() {
gameMode = "delay";
ship.gotoAndPlay("explode");
sndExplosion=new explosion_sound();
sndExplosionChannel=sndExplosion.play();
removeAllShieldIcons();
delayTimer = new Timer(2000,1);
delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE,newShip);
delayTimer.start();
removeShipIcon();
shipsLeft--;
}
// turn on shield for 3 seconds
public function startShield(freeShield:Boolean) {
if (shieldsLeft < 1) return; // no shields left
if (shieldOn) return; // shield already on
// turn on shield and set timer to turn off
ship.shield.visible = true;
sndShield=new shield_sound();
sndShieldChannel=sndShield.play();
shieldTimer = new Timer(3000,1);
shieldTimer.addEventListener(TimerEvent.TIMER_COMPLETE,endShield);
shieldTimer.start();
// update shields remaining
if (!freeShield) {
removeShieldIcon();
shieldsLeft--;
}
shieldOn = true;
}
// turn off shield
public function endShield(event:TimerEvent) {
ship.shield.visible = false;
shieldOn = false;
}
// ROCKS
// create a single rock of a specific size
public function newRock(x,y:int, rockType:String) {
trace("newRock fired");
// create appropriate new class
var newRock:MovieClip;
var rockRadius:Number;
if (rockType == "Big") {
newRock = new Rock_Big();
rockRadius = 35;
} else if (rockType == "Medium") {
newRock = new Rock_Medium();
rockRadius = 20;
} else if (rockType == "Small") {
newRock = new Rock_Small();
rockRadius = 10;
}
// choose a random look
newRock.gotoAndStop(Math.ceil(Math.random()*3));
// set start position
newRock.x = x;
newRock.y = y;
// set random movement and rotation
var dx:Number = Math.random()*2.0-1.0;
var dy:Number = Math.random()*2.0-1.0;
var dr:Number = Math.random();
// add to stage and to rocks list
gameObjects.addChild(newRock);
setChildIndex(gameObjects,1); // I added this
rocks.push({rock:newRock, dx:dx, dy:dy, dr:dr, rockType:rockType, rockRadius: rockRadius});
}
// create four rocks
public function nextRockWave(event:TimerEvent) {
rocks = new Array();
newRock(30,30,"Big"); //100 100
newRock(30,290,"Big"); // 100 300
newRock(450,30,"Big"); // 450 100
newRock(450,290,"Big"); // 450 300
gameMode = "play";
}
// animate all rocks
public function moveRocks(timeDiff:uint) {
for(var i:int=rocks.length-1;i>=0;i--) {
// move the rocks
var rockSpeed:Number = rockSpeedStart + rockSpeedIncrease*gameLevel;
rocks[i].rock.x += rocks[i].dx*timeDiff*rockSpeed;
rocks[i].rock.y += rocks[i].dy*timeDiff*rockSpeed;
// rotate rocks
rocks[i].rock.rotation += rocks[i].dr*timeDiff*rockSpeed;
// wrap rocks
if ((rocks[i].dx > 0) && (rocks[i].rock.x > 470)) {
rocks[i].rock.x -= 490;
}
if ((rocks[i].dx < 0) && (rocks[i].rock.x < -20)) {
rocks[i].rock.x += 490;
}
if ((rocks[i].dy > 0) && (rocks[i].rock.y > 325)) {
rocks[i].rock.y -= 345;
}
if ((rocks[i].dy < 0) && (rocks[i].rock.y < -25)) {
rocks[i].rock.y += 345;
}
}
}
public function rockHit(rockNum:uint) {
// create two smaller rocks
sndBubble=new bubble_sound();
sndBubbleChannel=sndBubble.play();
if (rocks[rockNum].rockType == "Big") {
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Medium");
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Medium");
} else if (rocks[rockNum].rockType == "Medium") {
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Small");
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Small");
}
// remove original rock
gameObjects.removeChild(rocks[rockNum].rock);
rocks.splice(rockNum,1);
}
// MISSILES
// create a new Missile
public function newMissile() {
// create
var newMissile:Missile = new Missile();
// set direction
newMissile.dx = Math.cos(Math.PI*ship.rotation/180);
newMissile.dy = Math.sin(Math.PI*ship.rotation/180);
// placement
newMissile.x = ship.x + newMissile.dx*shipRadius;
newMissile.y = ship.y + newMissile.dy*shipRadius;
// add to stage and array
gameObjects.addChild(newMissile);
missiles.push(newMissile);
}
// animate missiles
public function moveMissiles(timeDiff:uint) {
for(var i:int=missiles.length-1;i>=0;i--) {
// move
missiles[i].x += missiles[i].dx*missileSpeed*timeDiff;
missiles[i].y += missiles[i].dy*missileSpeed*timeDiff;
// moved off screen
if ((missiles[i].x < 0) || (missiles[i].x > 485) || (missiles[i].y < 0) || (missiles[i].y > 325)) {
gameObjects.removeChild(missiles[i]);
delete missiles[i];
missiles.splice(i,1);
}
}
}
// remove a missile
public function missileHit(missileNum:uint) {
gameObjects.removeChild(missiles[missileNum]);
missiles.splice(missileNum,1);
}
// GAME INTERACTION AND CONTROL
public function moveGameObjects(event:Event) {
// get timer difference and animate
var timePassed:uint = getTimer() - lastTime;
lastTime += timePassed;
moveRocks(timePassed);
if (gameMode != "delay") {
moveShip(timePassed);
}
moveMissiles(timePassed);
checkCollisions();
}
// look for missiles colliding with rocks
public function checkCollisions() {
// loop through rocks
rockloop: for(var j:int=rocks.length-1;j>=0;j--) {
// loop through missiles
missileloop: for(var i:int=missiles.length-1;i>=0;i--) {
// collision detection
if (Point.distance(new Point(rocks[j].rock.x,rocks[j].rock.y),
new Point(missiles[i].x,missiles[i].y))
< rocks[j].rockRadius) {
// remove rock and missile
rockHit(j);
missileHit(i);
// add score
gameScore += 10;
updateScore();
// break out of this loop and continue next one
continue rockloop;
}
}
// check for rock hitting ship
if (gameMode == "play") {
if (shieldOn == false) { // only if shield is off
if (Point.distance(new Point(rocks[j].rock.x,rocks[j].rock.y),
new Point(ship.x,ship.y))
< rocks[j].rockRadius+shipRadius) {
// remove ship and rock
shipHit();
rockHit(j);
}
}
}
}
// all out of rocks, change game mode and trigger more
if ((rocks.length == 0) && (gameMode == "play")) {
gameMode = "betweenlevels";
gameLevel++; // advance a level
levelTextBox.text = "Infection: " + gameLevel;
delayTimer = new Timer(2000,1);
delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE,nextRockWave);
delayTimer.start();
}
}
public function endGame() {
// remove all objects and listeners
removeChild(gameObjects);
removeChild(scoreObjects);
removeChild(gameBackground);
gameObjects = null;
scoreObjects = null;
removeEventListener(Event.ENTER_FRAME,moveGameObjects);
gameMode = "gameOver";
gotoAndStop("gameover");
}
/***** ADD COMMAS TO NUMBERS *******/
function addCommaInNumber (number : Number) : String
{
var integer : String = "" ;
var fraction : String = "" ;
var string : String = number.toString();
var array : Array = string.split(".");
var regex : RegExp = /(\d+)(\d{3})/;
integer = array[0];
while( regex.test(integer) )
{
integer = integer.replace(regex,'$1' + ',' + '$2');
}
if (array[1])
{ fraction = integer.length > 0 ? '.' + array[1] : ''; }
return integer + fraction;
}
}
}
The part of code you thought applied to your problem is incorrect.
A timer can be started along with it's declaration as :
private var myTimer:Timer = new Timer(delay, repeat);
But since you are not initiating the timer at the time of declaration (as seen in you snippet)
// timers
private var delayTimer:Timer;
private var shieldTimer:Timer;
There must be some other function where it would be initiated. Move the action of initiating the timer to whichever place you want to start the timer. For eg : into startspacerocks() function
If that is not the problem, please post the relevant code that applies to your problem.
EDIT:
Well I think your answer lies in the moveGameObjects function.
Try modifying the function as follows:
// GAME INTERACTION AND CONTROL
public function moveGameObjects(event:Event) {
//Current Time
var currentTime:uint = getTimer();
//Initiate lastTime
if(lastTime == 0) lastTime = currentTime;
// get timer difference and animate
var timePassed:uint = currentTime - lastTime;
lastTime += timePassed;
moveRocks(timePassed);
if (gameMode != "delay") {
moveShip(timePassed);
}
moveMissiles(timePassed);
checkCollisions();
}
From the code you've posted, I can't answer your question safely, but you should check, when startSpaceRocks() is called the first time. This should be in the click handler of your start button.
Beside that, your question title does not reflect the problem. There is no problem with a timer at all, there is a problem, when the "timer" is started.