How to get MovieClip.prototype in ActionScript 3? - actionscript-3

In a ActionScript 2 code sample it uses some MovieClip.prototype's functions, as MovieClip.prototype.setModel;
I'm trying to write this example using an ActionScript 3 class, but the MoviewClip.prototype does not exists, where can I get it from? Does it exist in ActionScript 3?
--update
Ok, as you are asking, here goes, this code works just fine as an ActionScript included on frame1, but I want to make a ActionScript 3 class with this same code:
//package
//{
// public class asteroids extends MovieClip
// {
var MW = 8; // Scaling factor for models (which were originally drawn on graph paper)
var SW = Stage.width; // Stage coords
var SH = Stage.height;
var kDegToRad = Math.PI/180; // Useful constant for drawing circles & such
var kDamp = 0.99; // Damping in ship acceleration
// The models
//
// Rocket fuselage
var fuseModel = [{mx:0, my:-5.5, x:0, y:-4, pen:.5, clr:0x000033, alpha:50},
{cx:-1,cy:-3,x:-1,y:-1, pen:2, clr:0x000033, alpha:50},
{x:-.75,y:4},
{cx:0, cy:4.5, x:.75,y:4}, // from -.75,4
{x:1,y:-1},
{cx:1,cy:-3,x:0,y:-4}];
// Rocket fins
var finModel = [ {mx:-1,my:-1,cx:-3,cy:4,x:-2,y:6,bf:0x0000FF,bfa:80},
{cx:-1,cy:4.5,x:-.75,y:4},
{x:-1,y:-1},
{mx:.75,my:4,cx:1,cy:4.5,x:2,y:6},
{cx:3,cy:4,x:1,y:-1},
{x:.75,y:4,ef:1}
];
// Routine to scale model to arbitrary size
function scaleModel(m,s)
{
for (var i = 0; i < m.length; ++i)
{
var pt = m[i];
if (pt.mx != undefined)
{
pt.mx *= s;
pt.my *= s;
}
if (pt.cx != undefined)
{
pt.cx *= s;
pt.cy *= s;
}
pt.x *= s;
pt.y *= s;
}
}
// Draw a model
//
function drawModel(m)
{
for (var i = 0; i < m.length; ++i)
{
var pt = m[i];
if (pt.bf != undefined)
this.beginFill(pt.bf, pt.bfa);
if (pt.pen != undefined)
this.lineStyle(pt.pen,pt.clr,pt.alpha);
if (pt.mx != undefined)
this.moveTo(pt.mx,pt.my);
if (pt.cx != undefined)
this.curveTo(pt.cx,pt.cy,pt.x,pt.y);
else if (pt.x != undefined)
this.lineTo(pt.x,pt.y);
if (pt.ef != undefined)
this.endFill();
}
}
// Ship Movement and most game-play stuff happens here
function ShipMove()
{
// Steering & Thrust
if (Key.isDown(Key.LEFT))
this._rotation -= 5;
else if (Key.isDown(Key.RIGHT))
this._rotation += 5;
if (Key.isDown(Key.CONTROL) || Key.isDown(Key.UP))
{
this.vx += Math.sin(this._rotation*kDegToRad);
this.vy -= Math.cos(this._rotation*kDegToRad);
}
else if (Key.isDown(Key.DOWN))
{
this.vx *= .9;
this.vy *= .9;
}
// Basic movement with acceleration and damping
this._x += this.vx;
this._y += this.vy;
// Wrap around edges of stage
if (this._x < -this._width)
this._x += SW+this._width*2;
else if (this._x > SW+this._width)
this._x -= SW+this._width*2;
if (this._y < -this._height)
this._y += SH+this._height*2;
else if (this._y > SH+this._height)
this._y -= SH+this._height*2;
}
// Initialize new ship
function NewShip()
{
ship_mc._x = SW/2;
ship_mc._y = SH/2;
ship_mc.onEnterFrame = shipMove;
}
// Assign a sprite model to a movieclip & draw it
//
MovieClip.prototype.setModel = function(m)
{
this.model = m;
this.drawModel(m);
}
MovieClip.prototype.drawModel = drawModel;
scaleModel(fuseModel, MW*.8); // Using a slightly smaller rocket than original drawing
scaleModel(finModel, MW*.8);
// One Time Initialziation
//
_root.createEmptyMovieClip("ship_mc", 2);
ship_mc.createEmptyMovieClip("fuselage", 1);
ship_mc.fuselage.setModel(fuseModel);
ship_mc.createEmptyMovieClip("fins", 2);
ship_mc.fins.setModel(finModel);
NewShip();
// }
//}

You should probably extend MovieClip and add the new functionality to the subclass, it's the best/proper way to go. Prototypes in AS2 are old, and were used when the language didn't support true OOP.

Using prototypes in AS3 is discouraged.
But there is a way to use it if you are compiling AS3 with the flex compiler.
First, you need to give a few compiler options.
PrototypeExtension-config.xml
<flex-config>
<compiler>
<as3>false</as3>
<es>true</es>
<strict>false</strict>
</compiler>
</flex-config>
PrototypeExtension.as
package {
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.Event;
import flash.geom.Point;
import flash.utils.getTimer;
public class PrototypeExtension extends Sprite {
public function PrototypeExtension() {
stage.align = "tl";
stage.scaleMode = "noScale";
MovieClip.prototype.move = function (x:int, y:int):void {
this.x = x; this.y = y;
};
MovieClip.prototype.tween = function (to:Point, duration:int):void {
var start:int = getTimer();
var from:Point = new Point(this.x, this.y);
var thisInstance:MovieClip = this;
this.addEventListener(Event.ENTER_FRAME, function tweener(e:Event):void {
var time:int = getTimer() - start;
if (time > duration) {
thisInstance.move(to.x, to.y);
thisInstance.removeEventListener(Event.ENTER_FRAME, tweener);
}
var t:Number = time / duration;
t = t * (2 - t);
var u:Number = 1 - t;
thisInstance.move(u * from.x + t * to.x, u * from.y + t *to.y);
});
}
var mc:MovieClip = new MovieClip;
mc.graphics.beginFill(0);
mc.graphics.drawRect(0, 0, 100, 100);
mc.graphics.endFill();
mc.tween(new Point(400, 300), 1000);
addChild(mc);
}
}
}
by
mxmlc PrototypeExtension.as
You can see how prototype extension is enabled in AS3.

Related

Having an issue with Flash Actionscript3

Wondering if you guys can help me. I've used online tutorials to create the following.
I am working on a small flash project and I've hit a wall. Basically, I've got 3 scenes. A home page, and 2 games. My home page and one of the games are programmed on the timeline within an actions layer. The third game is applied to a Main.as. The problem is that I want to apply a button called home to the Flappy game, but since I've used the .as file for this code, I'm unsure how to do it.
Basically, my question is "How do I add a button to the "Flappy" Scene? Each time i try to do it and run a test, It's playing the Flappy Game over the Scene 1.
Main.as ("Flappy" Scene3)
package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event; //used for ENTER_FRAME event
//import flash.events.MouseEvent;
public class Main extends MovieClip{
//These are all of the constants used.
const gravity:Number = 1.5; //gravity of the game. How fast ball falls
const dist_btw_obstacles:Number = 300; //distance between two obstacles
const ob_speed:Number = 8; //speed of the obstacle
const jump_force:Number = 15; //force with which it jumps
//variables
var player:Player = new Player();
var lastob:Obstacle = new Obstacle(); //varible to store the last obstacle in the obstacle array
var obstacles:Array = new Array(); //an array to store all the obstacles
var yspeed:Number = 0; //A variable representing the vertical speed of the bird
var score:Number = 0; //A variable representing the score
public function Main(){
init();
}
function init():void {
//initialize all the variables
player = new Player();
lastob = new Obstacle();
obstacles = new Array();
yspeed = 0;
score = 0;
//add player to center of the stage the stage
player.x = stage.stageWidth/2;
player.y = stage.stageHeight/2;
addChild(player);
//create 3 obstacles ()
createObstacle();
createObstacle();
createObstacle();
//Add EnterFrame EventListeners (which is called every frame) and KeyBoard EventListeners
addEventListener(Event.ENTER_FRAME,onEnterFrameHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, key_up);
}
private function key_up(event:KeyboardEvent){
if(event.keyCode == Keyboard.SPACE){
//If space is pressed then make the bird
yspeed = -jump_force;
}
}
function restart(){
if(contains(player))
removeChild(player);
for(var i:int = 0; i < obstacles.length; ++i){
if(contains(obstacles[i]) && obstacles[i] != null)
removeChild(obstacles[i]);
obstacles[i] = null;
}
obstacles.slice(0);
init();
}
function onEnterFrameHandler(event:Event){
//update player
yspeed += gravity;
player.y += yspeed;
//restart if the player touches the ground
if(player.y + player.height/2 > stage.stageHeight){
restart();
}
//Don't allow the sheep to go above the screen
if(player.y - player.height/2 < 0){
player.y = player.height/2;
}
//update obstacles
for(var i:int = 0;i<obstacles.length;++i){
updateObstacle(i);
}
//display the score
scoretxt.text = String(score);
}
//This functions update the obstacle
function updateObstacle(i:int){
var ob:Obstacle = obstacles[i];
if(ob == null)
return;
ob.x -= ob_speed;
if(ob.x < -ob.width){
//if an obstacle reaches left of the stage then change its position to the back of the last obstacle
changeObstacle(ob);
}
//If the bird hits an obstacle then restart the game
if(ob.hitTestPoint(player.x + player.width/2,player.y + player.height/2,true)
|| ob.hitTestPoint(player.x + player.width/2,player.y - player.height/2,true)
|| ob.hitTestPoint(player.x - player.width/2,player.y + player.height/2,true)
|| ob.hitTestPoint(player.x - player.width/2,player.y - player.height/2,true)){
restart();
}
//If the bird got through the obstacle without hitting it then increase the score
if((player.x - player.width/2 > ob.x + ob.width/2) && !ob.covered){
++score;
ob.covered = true;
}
}
//This function changes the position of the obstacle such that it will be the last obstacle and it also randomizes its y position
function changeObstacle(ob:Obstacle){
ob.x = lastob.x + dist_btw_obstacles;
ob.y = 100+Math.random()*(stage.stageHeight-200);
lastob = ob;
ob.covered = false;
}
//this function creates an obstacle
function createObstacle(){
var ob:Obstacle = new Obstacle();
if(lastob.x == 0)
ob.x = 800;
else
ob.x = lastob.x + dist_btw_obstacles;
ob.y = 100+Math.random()*(stage.stageHeight-200);
addChild(ob);
obstacles.push(ob);
lastob = ob;
}
}
}
Here is the code for my main page called "Scenery" (Scene 1) which is in an actions layer of timeline.
stop();
import flash.events.MouseEvent;
sun1.addEventListener(MouseEvent.CLICK,cloudy);
function cloudy (e:MouseEvent){
cloud1.x = cloud1.x + 10;
cloud2.x = cloud2.x - 10;
}
pong_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
function mouseDownHandler(event:MouseEvent):void {
gotoAndStop(1, "SheepyPong");
}
dodge_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler3);
function mouseDownHandler3(event:MouseEvent):void {
gotoAndStop(1, "Flappy");
}
This is my code for a very simple "SheepyPong" (Scene2) game which is linked to from front page:
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var velocityX:Number = 5;
var velocityY:Number = 5;
movieClip_1.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
movieClip_1.y -= 5;
}
if (downPressed)
{
movieClip_1.y += 5;
}
sheep.x += velocityX;
sheep.y += velocityY;
if(sheep.y + sheep.height/2 > stage.stageHeight || sheep.y - sheep.height/2 < 0){
velocityY *= -1
}
if(sheep.hitTestObject(AI) || sheep.hitTestObject(movieClip_1)){
velocityX *= -1;
}
if (sheep.x < 0) {
score2.text = (int(score2.text) +1).toString();
sheep.x = 275;
sheep.y = 200;
velocityX *= -1;
}
if (sheep.x > stage.stageWidth) {
score1.text = (int(score1.text) +1).toString();
sheep.x = 275;
sheep.y = 200;
velocityX *= -1;
}
AI.y = sheep.y;
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = true;
break;
}
case Keyboard.DOWN:
{
downPressed = true;
break;
}
}
}
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = false;
break;
}
case Keyboard.DOWN:
{
downPressed = false;
break;
}
}//end of switch
}//end of function
home_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler1);
function mouseDownHandler1(event:MouseEvent):void {
gotoAndStop(1, "Scenery");
}
I'm also getting this error in output when I run it. It's not actually affecting the outpu
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Main/onEnterFrameHandler()[/Users/mynamehere/Documents/Game/Main.as:91]
//This is line 91 in the Main.as file:
scoretxt.text = String(score);

Adding another Movie Clip into another Frame

I am attempting to add a new movie clip into the next frame of my shooter game.
I am using Actionscript 3.0
To give a basis of what I need help with for my assessment. When the score =50, switch to the next frame. And this is where I would like to add a new type of movie clip for the user to shoot!
Here is the code I have so far.
FRAME 1
//Tate's open screen
stop(); //makes the screen wait for events
paraBtn.addEventListener(MouseEvent.CLICK, playClicked); //this line is making your button an mouse click event
function playClicked(evt: MouseEvent): void { // now we are calling the event from this function and telling it to go to the next frame we labelled play
gotoAndStop("frame2");
// All rights of this music goes towards the makers of the game "Risk of Rain" which was made by Hapoo Games
}
FRAME 2 (Where the game actually starts)
stop();
// This plays the sound when left click is used
var spitSound: Sound = new Sound();
spitSound.load(new URLRequest("gunSound.mp3"));
//This plays the gameover sound when your lives reach 0
var overSound: Sound = new Sound();
overSound.load(new URLRequest("Gameover.mp3"));
//This plays the sound when you are hit
var etSound: Sound = new Sound();
etSound.load(new URLRequest("Urgh.mp3"));
//This sets the lives and points.
stage.addEventListener(MouseEvent.MOUSE_MOVE, aimTurret);
var points: Number = 0;
var lives: Number = 3;
var target: MovieClip;
var _health: uint = 100;
initialiseCursor();
//This variable stops the multiple errors with the move objects and bullets and range to stop compiling.
var Gameover: Boolean = false;
//This aims the turrent to where you mouse is on the screen
function aimTurret(evt: Event): void {
if (Gameover == false) {
gun.rotation = getAngle(gun.x, gun.y, mouseX, mouseY);
var distance: Number = getDistance(gun.x, gun.y, mouseX, mouseY);
var adjDistance: Number = distance / 12 - 7;
}
}
function getAngle(x1: Number, y1: Number, x2: Number, y2: Number): Number {
var radians: Number = Math.atan2(y2 - y1, x2 - x1);
return rad2deg(radians);
}
function getDistance(x1: Number, y1: Number, x2: Number, y2: Number): Number {
var dx: Number = x2 - x1;
var dy: Number = y2 - y1;
return Math.sqrt(dx * dx + dy * dy);
}
function rad2deg(rad: Number): Number {
return rad * (180 / Math.PI);
}
//Starts lives and shows text next to the numbers
function initialiseCursor(): void {
Mouse.hide();
target = new Target();
target.x = mouseX;
target.y = mouseY;
target.mouseEnabled = false;
addChild(target);
stage.addEventListener(MouseEvent.MOUSE_MOVE, targetMove);
stage.addEventListener(MouseEvent.MOUSE_DOWN, targetDown);
stage.addEventListener(MouseEvent.MOUSE_UP, targetUp);
livesdisplay.text = String(lives) + " Lives Left";
pointsdisplay.text = String(points) + " Points";
}
function targetMove(evt: MouseEvent): void {
target.x = this.mouseX;
target.y = this.mouseY;
}
function targetDown(evt: MouseEvent): void {
target.gotoAndStop(2);
}
function targetUp(evt: MouseEvent): void {
target.gotoAndStop(1);
}
//Starts bullets and speed of bullets, also addding new arrays for baddies
var gunLength: uint = 90;
var bullets: Array = new Array();
var bulletSpeed: uint = 20;
var baddies: Array = new Array();
stage.addEventListener(MouseEvent.MOUSE_DOWN, fireGun);
function fireGun(evt: MouseEvent) {
if (Gameover == false) {
var bullet: Bullet = new Bullet();
bullet.rotation = gun.rotation;
bullet.x = gun.x + Math.cos(deg2rad(gun.rotation)) * gunLength;
bullet.y = gun.y + Math.sin(deg2rad(gun.rotation)) * gunLength;
addChild(bullet);
bullets.push(bullet);
spitSound.play();
}
}
function deg2rad(deg: Number): Number {
return deg * (Math.PI / 180);
}
stage.addEventListener(Event.ENTER_FRAME, moveObjects);
function moveObjects(evt: Event): void {
if (Gameover == false) {
moveBullets();
moveBaddies();
}
}
function moveBullets(): void {
for (var i: int = 0; i < bullets.length; i++) {
var dx = Math.cos(deg2rad(bullets[i].rotation)) * bulletSpeed;
var dy = Math.sin(deg2rad(bullets[i].rotation)) * bulletSpeed;
bullets[i].x += dx;
bullets[i].y += dy;
if (bullets[i].x < -bullets[i].width || bullets[i].x > stage.stageWidth + bullets[i].width || bullets[i].y < -bullets[i].width || bullets[i].y > stage.stageHeight + bullets[i].width) {
removeChild(bullets[i]);
bullets.splice(i, 1);
}
}
}
// This is the start of the timer
var timer: Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, addBaddie);
timer.start();
// Adding army men on a timer and only from the top side
function addBaddie(evt: TimerEvent): void {
var baddie: Baddie = new Baddie();
var side: Number = Math.ceil(Math.random() * 1);
if (side == 1) {
baddie.x = Math.random() * stage.stageWidth;
baddie.y = -baddie.height;
}
baddie.angle = getAngle(baddie.x, baddie.y, gun.x, gun.y);
baddie.speed = 7;
addChild(baddie);
baddies.push(baddie);
}
function moveBaddies(): void {
for (var i: int = 0; i < baddies.length; i++) {
var dx = Math.cos(deg2rad(baddies[i].angle)) * baddies[i].speed;
var dy = Math.sin(deg2rad(baddies[i].angle)) * baddies[i].speed;
baddies[i].x += dx;
baddies[i].y += dy;
if (baddies[i].hitTestPoint(gun.x, gun.y, true)) {
removeChild(baddies[i]);
baddies.splice(i, 1);
loseLife();
//If baddie was removed then we don’t check for bullet hits
} else {
checkForHit(baddies[i]);
}
}
}
function checkForHit(baddie: Baddie): void {
for (var i: int = 0; i < bullets.length; i++) {
if (baddie.hitTestPoint(bullets[i].x, bullets[i].y, true)) {
removeChild(baddie);
points++;
if (points == 50) {
gotoAndStop("frame3")
}
pointsdisplay.text = String(points) + " Points";
baddies.splice(baddies.indexOf(baddie), 1);
}
}
}
// Keeping track of lost lives and when hitting 0 doing to frame four, also displaying "Lose life!"
function loseLife(): void {
etSound.play();
lives--;
if (lives == 0) {
Gameover = true;
overSound.play();
gotoAndStop("frame4")
}
livesdisplay.text = String(lives) + " Lives Left";
trace("Lose Life!");
}
FRAME 3 (This is where I need help, to add another movie clip) (I have made one for the frame named, "BaddieRed" With the Linkage being "Baddiered"
stop();
// The code from frame2 carries over and works the same in this frame
FRAME 4 (This is the screen where it's gameover)
stop();
timer.stop();
// User need to close by pressing the close button
//And restart the game manually
Is this what you're trying to achieve? Something like...
function addBaddie(evt: TimerEvent): void
{
var baddie : MovieClip;
if (points < 50) { var bad1: Baddie = new Baddie(); baddie = bad1; }
if (points >= 50) { var bad2 : Baddiered = new Baddiered(); baddie = bad2; }
var side: Number = Math.ceil(Math.random() * 1);
if (side == 1)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y -= baddie.height;
}
baddie.angle = getAngle(baddie.x, baddie.y, gun.x, gun.y);
baddie.speed = 7;
addChild(baddie);
baddies.push(baddie);
}

Error 2025 when trying to removeChild, child not contained where it was added?

I am trying to code a tile-based level editor, in which the Main class adds Tile class instances as children of the 'tiles' movieclip when clicking/dragging the mouse.
I am able to add tiles to the container, and they show on stage, however I cannot remove any tiles when erasing them is enabled. It gives me the following error
Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at Main/Draw()
at Main/::Go()
Also, when I check if the tile is inside the tiles container, it tells me that the parent is null.
So, a little help? I tried checking other questions with similar issues but none seemed to be close to mine.
package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
//import flash.events.TimerEvent.updateAfterEvent;
public class Main extends MovieClip {
//containers
var lines:Sprite = new Sprite();
var tiles:Sprite = new Sprite();
// Grid data
var tileW:int = 20;
var tileH:int = 20;
var gridW:int = 20;//(inputWidth);
var gridH:int = 20;//(inputHeight);
var gridX:int = 50;
var grixY:int = 50;
var level:Array;
//Drawing variables
var go:Boolean = false;
var erase:Boolean = false;
var default_tile:int = 1;
var type:int;
var rect:Object = {x:100, y:50, width:(gridW * tileW)/100, height:(gridH * tileH)/100};
//menus
var sizeMenu:SizeMenu = new SizeMenu();
var current:Tile = new Tile();
public function Main():void {
//Flash alignment and resizing
stage.scaleMode=StageScaleMode.NO_SCALE;
stage.align=StageAlign.TOP_LEFT;
stage.addChild(lines);
lines.x = rect.x;
lines.y = rect.y;
stage.addChild(tiles);
tiles.x = rect.x;
tiles.y = rect.y;
stage.addChild(sizeMenu);
stage.addChild(current);
current.x = 50;
current.gotoAndStop(default_tile);
stage.addEventListener(MouseEvent.MOUSE_DOWN, Go);
stage.addEventListener(MouseEvent.MOUSE_UP, Go);
stage.addEventListener(MouseEvent.MOUSE_MOVE, Go);
stage.addEventListener(KeyboardEvent.KEY_DOWN, ToggleErase);
stage.addEventListener(KeyboardEvent.KEY_UP, ToggleErase);
Setup();
}
//Draws grid lines
private function Setup():void {
trace("Drawing Grid...");
// create an empty array
level = new Array(gridH);
for (var i=0; i < gridW; i++) {
level[i] = new Array(gridW);
}
// attach lines to create a grid
for (var k=0; k <= gridH; k++) {
var line = new Line();
line.name = "line"+k;
line.scaleX = rect.width;
line.y = tileH * k;
lines.addChild(line);
for (var j=0; j <= gridW; j++) {
line = new Line();
line.name = "line"+j+"_"+k;
line.scaleX = rect.height;
line.x = tileW * j;
line.rotation = 90;
lines.addChild(line);
}
}
type = default_tile;
trace("Done drawing grid!");
}
//Decided if drawing is possible
private function Go(e:MouseEvent):void {
if (e.type == "mouseDown") {
go = true;
Draw(e);
}
if (e.type == "mouseUp") {
go = false;
}
if (e.type == "mouseMove") {
if (go) {
Draw(e);
}
//e.updateAfterEvent();
}
}
//Toggles erase
private function ToggleErase(e:KeyboardEvent):void{
if (e.shiftKey){
erase = true;
}
if (e.type == "keyUp"){
erase = false;
}
}
// attaches the tiles when drawn on the grid
public function Draw(e:MouseEvent) {
var x = mouseX;
var y = mouseY;
var cx = Math.floor((x - rect.x) / tileW);
var cy = Math.floor((y - rect.y) / tileH);
if (cx >= 0 && cx < gridW && cy >= 0 && cy < gridH) {
var target = e.currentTarget;
if (!erase) {
if (tiles.contains(target)){
trace("Contained!");
tiles.removeChild(target);
}
var tile = new Tile();
tiles.addChild(tile);
tile.name = ("t_" + cy + "_" + cx);
tile.x = (tileW * cx);
tile.y = (tileH * cy);
tile.gotoAndStop(type);
level[cy][cx] = type;
} else {
if (tiles.contains(target)){
trace("Contained!");
tiles.removeChild(target);
}
level[cy][cx] = default_tile - 1;
}
}
}
//Cleans the grid and redraws it
private function ResetGrid():void {
level = null;
//Delete tiles
while (tiles.numChildren) {
tiles.removeChildAt(0);
}
//Delete lines
while (lines.numChildren) {
lines.removeChildAt(0);
}
gridW=20;
gridH=20;
rect.width = (gridW * tileW)/100;
rect.height = (gridH * tileH)/100;
}
// updates the current-clip
private function update() {
current.gotoAndStop(type);
}
}
}
The following code is causing the problem, basically you are calling removeChild twice for the same object.
if (tiles.contains(target)){
trace("Contained!");
tiles.removeChild(target);
}
tiles.removeChild(target);
In your code, I notice that you have the ability for the tile to be removed, and then try to remove it again at the end of this block :
if (!erase) {
if (tiles.contains(target)){
trace("Contained!");
tiles.removeChild(target);
}
var tile = new Tile();
tiles.addChild(tile);
tile.name = ("t_" + cy + "_" + cx);
tile.x = (tileW * cx);
tile.y = (tileH * cy);
tile.gotoAndStop(type);
level[cy][cx] = type;
} else {
if (tiles.contains(target)){
trace("Contained!");
tiles.removeChild(target);
}
// this is going to throw an error
tiles.removeChild(target);
Make it easy on yourself and create a class for Tile with a remove method. Something like this:
class Tile extends Sprite
{
public function remove():void
{
if(parent) parent.removeChild(this);
}
}
This way, you can simply do:
tile.remove();
I have resolved my issue! All tile instances are given a name based on their position on the grid when added. Instead of making target the object the mouse was pointing at, I used getChildByName(); to search if there was already an object with a specific name, and to erase it if it did.
if (cx >= 0 && cx < gridW && cy >= 0 && cy < gridH) {
var target = tiles.getChildByName("t_" + cy + "_" + cx);
if (!erase) {
if (target){
tiles.removeChild(target);
}
var tile = new Tile();
tiles.addChild(tile);
tile.name = ("t_" + cy + "_" + cx);
tile.x = (tileW * cx);
tile.y = (tileH * cy);
tile.gotoAndStop(type);
level[cy][cx] = type;
} else {
if (target){
tiles.removeChild(target);
}
level[cy][cx] = default_tile - 1;
}
}

Making a simple chase AI in AS3

im attempting to make a simple game where zombies spawn out randomly from the edges of the screen and once they have spawned, they will get the last position of the player and keep moving towards that direction until they hit the stage and gets removed. However, i seem to be having a problem with the chase code. Even after reading tons of articles that offer the same chunk of code, im still unable to make it work (IM DOING IT WRONG ARRGH).
This is the main class
package
{
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.ui.*;
public class main extends MovieClip
{
private var left,right,up,down,fire,mouseRight,mouseLeft:Boolean;
private var speedX,speedY,mobPosX,mobPosY:int;
private var num:Number;
private var wizard:Player;
private var crosshair:Crosshair;
private var mobArray,magicArray:Array;
public function main()
{
//Hide mouse for crosshair
Mouse.hide();
crosshair = new Crosshair();
addChild(crosshair);
crosshair.x = stage.stageWidth;
crosshair.y = stage.stageHeight;
//Set initial speed
speedX = 0;
speedY = 0;
//Wizard stuff
fire = false;
wizard = new Player();
addChild(wizard);
wizard.x = stage.stageWidth / 2;
wizard.y = stage.stageHeight / 2;
//Mob stuff
mobArray = new Array();
magicArray = new Array();
//Initialize bool so movement doesn't get stuck on startup
up = false;
down = false;
left = false;
right = false;
}
public function startGame()
{
addEventListener(Event.ENTER_FRAME,update);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
stage.addEventListener(MouseEvent.CLICK, myClick);
}
private function keyDownHandler(evt:KeyboardEvent)
{
if (evt.keyCode == 37)
{
left = true;
}
if (evt.keyCode == 38)
{
up = true;
}
if (evt.keyCode == 39)
{
right = true;
}
if (evt.keyCode == 40)
{
down = true;
}
if (evt.keyCode == 67)
{
trace(mobArray.length);
}
}
private function keyUpHandler(evt:KeyboardEvent)
{
if (evt.keyCode == 37)
{
left = false;
speedX = 0;
}
if (evt.keyCode == 38)
{
up = false;
speedY = 0;
}
if (evt.keyCode == 39)
{
right = false;
speedX = 0;
}
if (evt.keyCode == 40)
{
down = false;
speedY = 0;
}
}
function myClick(eventObject:MouseEvent)
{
fire = true;
}
public function update(evt:Event)
{
//UI
crosshair.x = mouseX;
crosshair.y = mouseY;
//Start player
if (left && right == false)
{
speedX = -8;
}
if (up && down == false)
{
speedY = -8;
}
if (down && up == false)
{
speedY = 8;
}
if (right && left == false)
{
speedX = 8;
}
wizard.x += speedX;
wizard.y += speedY;
for (var i = mobArray.length - 1; i >= 0; i--)
{
//Start mob //if X is zero and Y > 10, spawn.
var m:Zombie = new Zombie();
m.chase((Math.atan2(mobArray[i].y - wizard.y,mobArray[i].x - wizard.x)/Math.PI * 180)); //applies trigo
num = Math.random();
if (num < 0.1)
{
//when x = 0
mobPosX = 10;
mobPosY = Math.floor(Math.random() * 590) + 10;
}
else if (num < 0.3)
{
//when y = 0
mobPosX = Math.floor(Math.random() * 790) + 10;
mobPosY = 10;
}
else if (num < 0.6)
{
mobPosX = 800;
mobPosY = Math.floor(Math.random() * 590) + 10;
//when x width of screen
}
else if (num < 0.9)
{
//y is height of screen
mobPosX = Math.floor(Math.random() * 790) + 10;
mobPosY = 590;
}
m.x = mobPosX;
m.y = mobPosY;
mobArray.push(m);
addChild(m);
}
}
private function gameOver()
{
removeEventListener(Event.ENTER_FRAME,update);
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
}
}//end class
}//end package
This is the zombie class
package
{
import flash.display.*;
import flash.events.*;
public class Zombie extends MovieClip
{
private var zombSpd:Number;
private var angle:Number;
public function Zombie()
{
zombSpd = 10;
}
public function chase(chaseAngle:Number)
{
angle = chaseAngle;
}
public function update()
{
this.x+=Math.cos(angle*Math.PI/180)*zombSpd;
this.y+=Math.sin(angle*Math.PI/180)*zombSpd;
}
}//end class
}//end package
Thank you :)
I just reread your code and see that you must read and learn more about programming before trying to create a game like this.
the reason your zombies are not spawning are because you never get inside the for loop. mob array length will be zero to start with, so the for loop will never happen.
take that for loop out and create a function to spawn enemies in your main class. you can use the code you use in your for loop as the code for this function example:
function spawn():void{
//code directly from your for loop, with a small change
num = Math.random();
if (num < 0.1)
{
//when x = 0
mobPosX = 10;
mobPosY = Math.floor(Math.random() * 590) + 10;
}
else if (num < 0.3)
{
//when y = 0
mobPosX = Math.floor(Math.random() * 790) + 10;
mobPosY = 10;
}
else if (num < 0.6)
{
mobPosX = 800;
mobPosY = Math.floor(Math.random() * 590) + 10;
//when x width of screen
}
else if (num < 0.9)
{
//y is height of screen
mobPosX = Math.floor(Math.random() * 790) + 10;
mobPosY = 590;
}
var m:Zombie = new Zombie();
m.x = mobPosX;
m.y = mobPosY;
m.chase((Math.atan2(m.y - wizard.y,m.x - wizard.x)/Math.PI * 180)); //applies trigo
mobArray.push(m);
addChild(m);
}
now in your update function you must determine when you want enemies to spawn. you can do this by using a counter. Ill let you figure that part out, but if you want zombies to spawn continuously, (where your forloop in the update function was) add this:
//use a counter variable to determine when to execute spawn
spawn();
//loop through all zombies
for(var i:int = 0; i < mobArray.length; i++){
mobArray[i].update();
}
Steering behavior example at AdvanceEDActionScriptAnimation with abstracted interfaces and marshaling implementation.
Github:https://github.com/yangboz/as3SteeringBehavior

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.