AS3 1084: Syntax error: expecting rightparen before colon - actionscript-3

i'm trying to make an AS3 shooting game, which is player right to left.
I want to make it so that, when i shoot (spawnKogel) shootAllow becomes false, and then initiates kogelCheck, which checks if the bullet (Kogel) is < -10. If that's true, shootAllow becomes True, and i can shoot again.
But i'm getting the error in the title, at the end of the spawnKogel, when I try to initialize kogelCheck. Here's my code:
package
{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.ui.Keyboard;
import flash.ui.Mouse;
import flash.events.MouseEvent;
import flash.display.Stage;
import flash.media.Sound;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class amateurodius extends MovieClip
{
public var schip:ruimteschip = new ruimteschip();
public var Kogel = new Bullet();
var sound = new lazor();
var BGM = new Muziek();
var backdrop = new background();
var shootAllow:Boolean = true;
public function amateurodius()
{
addEventListener(Event.ADDED_TO_STAGE, initialize);
addEventListener(Event.ENTER_FRAME, vijandmaken);
stage.addEventListener(KeyboardEvent.KEY_DOWN, spawnKogel);
addEventListener(Event.ENTER_FRAME, kogelCheck);
Mouse.hide();
}
function initialize(e:Event)
{
addChild(backdrop);
addChild(schip);
BGM.play();
}
function spawnKogel(e:KeyboardEvent):void
{
if (shootAllow == true)
{
if (e.keyCode == Keyboard.SPACE)
{
addChild(Kogel);
Kogel.x = schip.x;
Kogel.y = schip.y;
sound.play();
shootAllow = false;
kogelCheck (e:Event);
}
}
}
function kogelCheck (e:Event)
{
if (Kogel.x < -30)
{
shootAllow == true;
}
else
{
shootAllow == false;
}
}

Remove the type from event when you call kogelCheck:
// Just passing on the event, doesn't need type declaration
kogelCheck (e);

Related

How to add a unique function to all the movieclips in AS3?

I would like to add a specific function to every movieclip. I've added an event listener but all the movieclips are doing the same thing.
I've noticed that I can't do it with the i variable because it's 11 could you help me find another way?
package
{
import flash.desktop.NativeApplication;
import flash.desktop.SystemIdleMode;
import flash.display.MovieClip;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageOrientation;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.events.StageOrientationEvent;
import flash.system.Capabilities;
import flash.text.TextField;
import flash.ui.Keyboard;
import com.thanksmister.touchlist.renderers.TouchListItemRenderer;
import com.thanksmister.touchlist.events.ListItemEvent;
import com.thanksmister.touchlist.controls.TouchList;
[SWF( width = '480', height = '800', backgroundColor = '#000000', frameRate = '24')]
public class AS3ScrollingList extends MovieClip
{
private var touchList:TouchList;
private var textOutput:TextField;
private var stageOrientation:String = StageOrientation.DEFAULT;
public function AS3ScrollingList()
{
// needed to scale our screen
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
if(stage)
init();
else
stage.addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
stage.removeEventListener(Event.ADDED_TO_STAGE, init);
stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);
stage.addEventListener(Event.RESIZE, handleResize);
// if we have autoOrients set in permissions we add listener
if(Stage.supportsOrientationChange) {
stage.addEventListener(StageOrientationEvent.ORIENTATION_CHANGE, handleOrientationChange);
}
if(Capabilities.cpuArchitecture == "ARM") {
NativeApplication.nativeApplication.addEventListener(Event.ACTIVATE, handleActivate, false, 0, true);
NativeApplication.nativeApplication.addEventListener(Event.DEACTIVATE, handleDeactivate, false, 0, true);
}
// add our list and listener
touchList = new TouchList(stage.stageWidth, stage.stageHeight);
touchList.addEventListener(ListItemEvent.ITEM_SELECTED, handlelistItemSelected);
addChild(touchList);
// Fill our list with item rendreres that extend ITouchListRenderer.
for(var i:int = 1; i < 3; i++) {
var item:TouchListItemRenderer = new TouchListItemRenderer();
item.index = i;
item.data = "This is list item " + String(i);
item.itemHeight = 120;
item.addEventListener(MouseEvent.CLICK, gotostore);
item.buttonMode = true;
touchList.addListItem(item);
}
//not nested function
function gotostore (e:MouseEvent) {
switch(e.currentTarget.name) {
case "firstMovieClip":
trace("buton1");
//first movieclip clicked
break;
case "secondMovieClip":
trace("buton2");
//second movieclip clicked
break;
//etc...
}
}
}
/**
* Handle stage orientation by calling the list resize method.
* */
private function handleOrientationChange(e:StageOrientationEvent):void
{
switch (e.afterOrientation) {
case StageOrientation.DEFAULT:
case StageOrientation.UNKNOWN:
//touchList.resize(stage.stageWidth, stage.stageHeight);
break;
case StageOrientation.ROTATED_RIGHT:
case StageOrientation.ROTATED_LEFT:
//touchList.resize(stage.stageHeight, stage.stageWidth);
break;
}
}
private function handleResize(e:Event = null):void
{
touchList.resize(stage.stageWidth, stage.stageHeight);
}
private function handleActivate(event:Event):void
{
NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE;
}
private function handleDeactivate(event:Event):void
{
NativeApplication.nativeApplication.exit();
}
/**
* Handle keyboard events for menu, back, and seach buttons.
* */
private function handleKeyDown(e:KeyboardEvent):void
{
if(e.keyCode == Keyboard.BACK) {
e.preventDefault();
NativeApplication.nativeApplication.exit();
} else if(e.keyCode == Keyboard.MENU){
e.preventDefault();
} else if(e.keyCode == Keyboard.SEARCH){
e.preventDefault();
}
}
/**
* Handle list item seleced.
* */
private function handlelistItemSelected(e:ListItemEvent):void
{
trace("List item selected: " + e.renderer.index);
}
}
}
Your gotostore function is a nested function which is a really bad design practice, do not use nested functions. You can check which movieclip did the user click with the e.currentTarget.name, this will give you the INSTANCE NAME of the movieclip which the user "selected".
for(var i:int = 1; i < 11; i++) {
var item:TouchListItemRenderer = new TouchListItemRenderer();
item.index = i;
item.data = "This is list item " + String(i);
item.itemHeight = 120;
item.addEventListener(MouseEvent.CLICK, gotostore);
item.buttonMode = true;
touchList.addListItem(item);
}
//not nested function
function gotostore (e:MouseEvent) {
switch(e.currentTarget.name) {
case "firstMovieClip":
//first movieclip clicked
break;
case "secondMovieClip":
//second movieclip clicked
break;
//etc...
}
}

ActionScript 3: Zoom functions - drag does not show

I've included a zoom functionality similar to the one explained at this website: http://www.flashandmath.com/howtos/zoom/
Even though it does indeed work in terms of the possibility of moving the image on my stage, the drag-animation is not present, meaning there will be no "movement" of my image, just a sudden change in position.
The problem followed my attempt to change the concept from timeline-based to class-based.
Here is my Main class:
package
{
import flash.display.MovieClip;
import flash.utils.Dictionary;
import flash.display.Shape;
import fl.transitions.Fly;
import fl.motion.MatrixTransformer;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.ui.Mouse;
public class Main extends Sprite
{
public static var scale:Number = 1;
private var _rootMC:MovieClip;
// ------------------------------
public var bg_image:Sprite;
public var spImage:Sprite;
public var mat:Matrix;
public var mcIn:MovieClip;
public var mcOut:MovieClip;
public var boardWidth:int = 980;
public var boardHeight:int = 661;
public var boardMask:Shape;
public var externalCenter:Point;
public var internalCenter:Point;
public static var scaleFactor:Number = 0.8;
public static var minScale:Number = 0.25;
public static var maxScale:Number = 10.0;
//-------------------------------
public function Main(rootMC:MovieClip)
{
_rootMC = rootMC;
bg_image = new image();
this.graphics.beginFill(0xB6DCF4);
this.graphics.drawRect(0,0,boardWidth,boardHeight);
this.graphics.endFill();
spImage = new Sprite();
this.addChild(spImage);
boardMask = new Shape();
boardMask.graphics.beginFill(0xDDDDDD);
boardMask.graphics.drawRect(0,0,boardWidth,boardHeight);
boardMask.graphics.endFill();
boardMask.x = 0;
boardMask.y = 0;
this.addChild(boardMask);
spImage.mask = boardMask;
minScale = boardWidth / bg_image.width;
mcIn = new InCursorClip();
mcOut = new OutCursorClip();
bg_image.addChild(mcIn);
bg_image.addChild(mcOut);
bg_image.scaleX = minScale;
bg_image.scaleY = minScale;
spImage.addChild(bg_image);
spImage.addChild(mcIn);
spImage.addChild(mcOut);
spImage.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
_rootMC.stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
spImage.addEventListener(MouseEvent.CLICK, zoom);
_rootMC.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler);
_rootMC.stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
}
private function startDragging(mev:MouseEvent):void
{
spImage.startDrag();
}
private function stopDragging(mev:MouseEvent):void
{
spImage.stopDrag();
}
private function zoom(mev:MouseEvent):void
{
if ((!mev.shiftKey)&&(!mev.ctrlKey))
{
return;
}
if ((mev.shiftKey)&&(mev.ctrlKey))
{
return;
}
externalCenter = new Point(spImage.mouseX,spImage.mouseY);
internalCenter = new Point(bg_image.mouseX,bg_image.mouseY);
if (mev.shiftKey)
{
bg_image.scaleX = Math.max(scaleFactor*bg_image.scaleX, minScale);
bg_image.scaleY = Math.max(scaleFactor*bg_image.scaleY, minScale);
}
if (mev.ctrlKey)
{
bg_image.scaleX = Math.min(1/scaleFactor*bg_image.scaleX, maxScale);
bg_image.scaleY = Math.min(1/scaleFactor*bg_image.scaleY, maxScale);
}
mat = this.transform.matrix.clone();
MatrixTransformer.matchInternalPointWithExternal(mat,internalCenter,externalCenter);
bg_image.transform.matrix = mat;
}
private function keyHandler(ke:KeyboardEvent):void
{
mcIn.x = spImage.mouseX;
mcIn.y = spImage.mouseY;
mcOut.x = spImage.mouseX;
mcOut.y = spImage.mouseY;
mcIn.visible = ke.ctrlKey;
mcOut.visible = ke.shiftKey;
if (ke.ctrlKey || ke.shiftKey)
{
Mouse.hide();
}
else
{
Mouse.show();
}
}
}
}
Here is my image class:
package {
import fl.motion.MatrixTransformer;
import flash.display.MovieClip;
import flash.utils.Dictionary;
import flash.display.Shape;
import fl.transitions.Fly;
import fl.motion.MatrixTransformer;
import flash.events.MouseEvent;
public class image extends MovieClip
{
public function image()
{
this.width = 980
this.height = 500
this.y = 0
this.x = 0
}
}
I know this is a lot of code, but I am really stuck :(
On your MOUSE_DOWN handler, you need to start listening to the MOUSE_MOVE event.
On your MOUSE_UP handler, you need to stop listening to the MOUSE_MOVE event.
Not sure if you are already doing this.
In your MOUSE_MOVE event handler, you need to update the x / y positions of the image, in a similar way to what you are probably doing on the MOUSE_UP handler.

as3 hitTestPoint detecting alpha

I am trying to make maze where the user draws with mouse and if they hit the wall it erases the line they just drew. I have a png file with alpha that creates the walls of the maze.
I need the user to draw on the alpha but when they hit a non alpha it will trigger an action and erase the line.
Here is the line I am having issues with:
if (myshape.hitTestPoint(theBall.x,theBall.y, true))
Here is the full code:
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.JointStyle;
import flash.display.LineScaleMode;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.*;
public class MazeClass extends Sprite
{
//Are we drawing or not?
private var drawing:Boolean;
public var myshape:Shape;
public var alreadyDrawn:Shape;
public var theBall:Ball = new Ball();
//alreadyDrawn = new Shape();
public function MazeClass()
{
if (stage)
{
myshape = new Shape();
myshape.graphics.lineStyle(12,0x000000);
addChild(myshape);
drawing = false;//to start with
stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
stage.addEventListener(MouseEvent.MOUSE_MOVE, draw);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDrawing);
//stage.addEventListener(Event.ENTER_FRAME, checkIt);
addChild(theBall);
}
}
public function startDrawing(event:MouseEvent):void
{
myshape.graphics.moveTo( mouseX, mouseY);
drawing = true;
}
public function draw(event:MouseEvent)
{
if (drawing)
{
//checkIt();
myshape.graphics.lineTo(mouseX,mouseY);
if (myshape.hitTestPoint(theBall.x,theBall.y, true))
{
trace("Hit A WALL!");
myshape.graphics.clear();
myshape.graphics.lineStyle(12, 0xFFFFFF);
myshape.graphics.moveTo(mouseX,mouseY);
}
}
}
public function stopDrawing(event:MouseEvent)
{
drawing = false;
}
}
}
Another option is to test the colour of the map bitmapdata pixel that corresponds to the "player's position" (the end of the drawn line, in this case):
var testPixel:uint = _myBitmapData.getPixel(xPosition, yPosition);
Or you can use .getPixel32 which includes alpha in the returned uint.
I FOUND A WORKING SOLUTION:
I found a working solution thanks to fsbmain. Thank you. I am posting my full code in hopes that this can help someone else.
In the end I had to use another movieClip rather than the mouse, but this worked for me. Now instead of drawing anywhere in the maze they have to drag a little character named Beau thru the maze. This works better for me.
It would be nice to know how to also detect if the mouse or the actual line I am drawing hit the wall as well. Maybe someone can make a suggestion. Nevertheless, thanks for helping me get this far.
The short and essential code to make my movieClip detect the alpha can be found here. It really is very short compared to other complicated options I found. Here is the link: http://www.mikechambers.com/blog/2009/06/24/using-bitmapdata-hittest-for-collision-detection/
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.JointStyle;
import flash.display.LineScaleMode;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.*;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.desktop.NativeApplication;
import flash.system.Capabilities;
import flash.display.*;
import flash.geom.*;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Matrix;
public class MazeClass extends Sprite
{
//Are we drawing or not?
private var drawing:Boolean;
public var myshape:Shape;
public var alreadyDrawn:Shape;
public var theMap:*;
public var swiper:Swiper = new Swiper();
public var Beau:littleBeau = new littleBeau();
//alreadyDrawn = new Shape();
public var currentGalleryItem:Number = 1;
public var totalGalleryItems:Number = 4;
public var redClipBmpData:BitmapData;
public var blueClipBmpData:BitmapData;
public var redRect:Rectangle;
public var blueRect:Rectangle;
public function MazeClass()
{
if (stage)
{
theMap = new MapOne();
myshape = new Shape();
myshape.graphics.lineStyle(33,0x0aa6df);
addChild(myshape);
drawing = false;//to start with
stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
stage.addEventListener(MouseEvent.MOUSE_MOVE, draw);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDrawing);
//stage.addEventListener(Event.ENTER_FRAME, checkIt);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_OptionsMenuHandler);
Multitouch.inputMode = MultitouchInputMode.GESTURE;
addChild(theMap);
//theMap.height = stage.stageHeight - 200;
theMap.theStart.alpha = 0;
theMap.theFinish.alpha = 0;
addChild(swiper);
swiper.y = stage.stageHeight - swiper.height;
swiper.addEventListener(TransformGestureEvent.GESTURE_SWIPE, fl_SwipeToGoToNextPreviousFrame);
addChild(Beau);
Beau.x = theMap.theStart.x;
Beau.y = theMap.theStart.y - swiper.height;
Beau.addEventListener(MouseEvent.MOUSE_DOWN, BeauStartDrag);
Beau.addEventListener(MouseEvent.MOUSE_UP, BeauStopDrag);
redRect = theMap.getBounds(this);
redClipBmpData = new BitmapData(redRect.width,redRect.height,true,0);
redClipBmpData.draw(theMap);
blueRect = Beau.getBounds(this);
blueClipBmpData = new BitmapData(blueRect.width,blueRect.height,true,0);
blueClipBmpData.draw(Beau);
//blueClipBmpData.x = theMap.theStart.x;
//blueClipBmpData.y = theMap.theStart.y - swiper.height;
stage.addEventListener(Event.ENTER_FRAME, enterFrame);
}
}
public function enterFrame(e:Event):void
{
//Beau.x = mouseX;
//Beau.y = mouseY;
if (redClipBmpData.hitTest(new Point(theMap.x, theMap.y),
255,
blueClipBmpData,
new Point(Beau.x, Beau.y),
255
))
{
trace("hit");
clearAll();
//redClip.filters = [new GlowFilter()];
}
else
{
trace("No Hit");
}
}
public function BeauStartDrag(event:MouseEvent):void
{
Beau.startDrag();
drawing = true;
}
public function BeauStopDrag(event:MouseEvent):void
{
drawing = false;
Beau.stopDrag();
}
public function startDrawing(event:MouseEvent):void
{
myshape.graphics.moveTo( mouseX, mouseY);
}
//drawing = true;
public function draw(event:MouseEvent)
{
if (drawing)
{
//checkIt();
myshape.graphics.lineTo(mouseX,mouseY);
}
}
public function stopDrawing(event:MouseEvent)
{
//drawing = false;
}
public function fl_OptionsMenuHandler(event:KeyboardEvent):void
{
if ((event.keyCode == 95) || (event.keyCode == Keyboard.MENU))
{
NativeApplication.nativeApplication.exit(0);
}
}
public function clearAll()
{
myshape.graphics.clear();
myshape.graphics.lineStyle(12, 0x0aa6df);
myshape.graphics.moveTo(mouseX,mouseY);
Beau.x = theMap.theStart.x;
Beau.y = theMap.theStart.y - swiper.height;
drawing = false;
Beau.stopDrag();
}
public function fl_SwipeToGoToNextPreviousFrame(event:TransformGestureEvent):void
{
if (event.offsetX == 1)
{
if (currentGalleryItem > 1)
{
currentGalleryItem--;
trace("swipe Right");
clearAll();
removeChild(theMap);
theMap = new MapOne();
addChild(theMap);
theMap.height = stage.stageHeight - 200;
theMap.theStart.alpha = 0;
theMap.theFinish.alpha = 0;
addChild(Beau);
Beau.x = theMap.theStart.x;
Beau.y = theMap.theStart.y - swiper.height;
}
}
else if (event.offsetX == -1)
{
if (currentGalleryItem < totalGalleryItems)
{
currentGalleryItem++;
trace("swipe Left");
clearAll();
removeChild(theMap);
theMap = new MapTwo();
addChild(theMap);
theMap.height = stage.stageHeight - 200;
theMap.theStart.alpha = 0;
theMap.theFinish.alpha = 0;
addChild(Beau);
Beau.x = theMap.theStart.x;
Beau.y = theMap.theStart.y - swiper.height;
}
}
}
}
}

Remove Child of Root actionscript3

I've created 4 instances of Notes and I have them moving to the right until their x value is greater than 100. Once they're there, how do I remove them? I ran a trace statement and confirmed that the parent of these instances is root (root1 to be exact). If I type
root.removeChild(this);
I get an error saying "call to a possibly undefined method removeChild"
If I type
removeChild(this);
I get an error saying "The supplied DisplayObject must be a child of the caller". Full code is posted below. The last line before the }'s at the end is the problem line. Thanks so much for the help!
package
{
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.utils.getDefinitionByName;
import flash.utils.Timer;
import flash.events.TimerEvent;
[Frame(factoryClass="Preloader")]
public class Main extends Sprite
{
private var speed:int = 8;
[Embed(source="../lib/Dodgethis.jpg")]
public var Notes:Class;
public var numnotes:Number;
public var timer:Timer = new Timer(500, 1)
public var rootContainer:DisplayObjectContainer = DisplayObjectContainer (root);
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
timer.start();
timer.addEventListener(TimerEvent.TIMER, testevent);
}
private function testevent(e:Event = null):void {
trace("testevent has run");
appear();
}
private function appear() {
var arr1:Array = new Array;
numnotes = 4;
for (var i = 0; i < numnotes; i++)
{
trace (i);
var nbm:Bitmap = new Notes;
stage.addChild(nbm);
nbm.y = i * 50;
arr1.push(nbm);
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
}
private function loop (e:Event):void {
this.x += speed;
trace(this.x) ;
if (this.x > 100) {
removeEventListener(Event.ENTER_FRAME, loop);
trace ("Event listener was removed");
//removeChild(this);
//rootContainer.removeChild (nbm);
/*trace(this.contains)
trace(this.name)
trace(this)*/
trace(this.parent.name); //root
removeChild(this);
}
}
}
}
Try using this in the loop function
e.target.parent.removeChild(e.target);
//or
stage.removeChild(e.target);
You're adding the notes to stage. So you need to remove them from stage.
stage.removeChild( note );
You can only remove a child from its parent, not from any other container. So calling removeChild on a different container will always fail

Showing main menu over objects / movieclips?

I am creating a game in Flash and I am creating a main menu for the game (With buttons like 'Play', 'How to Play', 'Hiscores' etc.) and was wondering what is the best way to go about it?
All of my Actionscript code is in external .as files and I've used classes throughout but I was having trouble figuring out how to get it so that the menu will be shown as soon as the game is ran. The main problem is that there are timers in my game that have event handlers attached to them and I was trying to think of the best way to essentially stop these timers until the user actually clicks 'Play', otherwise the objects spawn over the top of the menu and the timer ticks down.
Would stopping the timers but then adding an event handler to the play button to start the timers be a good idea? I am trying to figure out the best way to do this for future reference.
Thank you for any assistance.
Edit: Tried Cherniv's advice, getting some errors.
Main.as:
package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.ui.Mouse;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.system.LoaderContext;
import flash.display.Sprite;
import flash.net.Socket;
public class Main extends MovieClip {
public static var gameLayer:Sprite = new Sprite;
public static var endGameLayer:Sprite = new Sprite;
public static var menuLayer:Sprite = new Sprite;
public var gameTime:int;
public var levelDuration:int;
public var crosshair:crosshair_mc;
static var score:Number;
var enemyShipTimer:Timer;
var enemyShipTimerMed:Timer;
var enemyShipTimerSmall:Timer;
static var scoreHeader:TextField = new TextField();
static var scoreText:TextField = new TextField();
static var timeHeader:TextField = new TextField();
static var timeText:TextField = new TextField();
public function Main()
{
var mainMenu:myMenu = new myMenu;
addChild(gameLayer);
addChild(endGameLayer);
addChild(menuLayer);
playBtn.addEventListener(MouseEvent.CLICK, startButtonPressed);
}
function startButtonPressed(e:Event)
{
levelDuration = 30;
gameTime = levelDuration;
var gameTimer:Timer = new Timer(1000,levelDuration);
gameTimer.addEventListener(TimerEvent.TIMER, updateTime);
gameTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timeExpired)
gameTimer.start();
scoreHeader = new TextField();
scoreHeader.x = 5;
scoreHeader.text = String("Score: ");
gameLayer.addChild(scoreHeader);
scoreText = new TextField();
scoreText.x = 75;
scoreText.y = 0;
scoreText.text = String(0);
gameLayer.addChild(scoreText);
timeHeader = new TextField();
timeHeader.x = 490;
timeHeader.y = 0;
timeHeader.text = String("Time: ");
gameLayer.addChild(timeHeader);
timeText = new TextField();
timeText.x = 550;
timeText.y = 0;
timeText.text = gameTime.toString();
gameLayer.addChild(timeText);
var scoreFormat = new TextFormat("Arial Rounded MT Bold", 20, 0xFFFFFF);
scoreHeader.setTextFormat(scoreFormat);
scoreText.setTextFormat(scoreFormat);
timeHeader.setTextFormat(scoreFormat);
timeText.setTextFormat(scoreFormat);
enemyShipTimer = new Timer(2000);
enemyShipTimer.addEventListener("timer", sendEnemy);
enemyShipTimer.start();
enemyShipTimerMed = new Timer(2500);
enemyShipTimerMed.addEventListener("timer", sendEnemyMed);
enemyShipTimerMed.start();
enemyShipTimerSmall = new Timer(2750);
enemyShipTimerSmall.addEventListener("timer", sendEnemySmall);
enemyShipTimerSmall.start();
crosshair = new crosshair_mc();
gameLayer.addChild(crosshair);
crosshair.mouseEnabled = crosshair.mouseChildren = false;
Mouse.hide();
gameLayer.addEventListener(Event.ENTER_FRAME, moveCursor);
resetScore();
}
function sendEnemy(e:Event)
{
var enemy = new EnemyShip();
gameLayer.addChild(enemy);
gameLayer.addChild(crosshair);
}
function sendEnemyMed(e:Event)
{
var enemymed = new EnemyShipMed();
gameLayer.addChild(enemymed);
gameLayer.addChild(crosshair);
}
function sendEnemySmall(e:Event)
{
var enemysmall = new EnemyShipSmall();
gameLayer.addChild(enemysmall);
gameLayer.addChild(crosshair);
}
static function updateScore(points)
{
score += points;
scoreText.text = String(score);
var scoreFormat = new TextFormat("Arial Rounded MT Bold", 20, 0xFFFFFF);
scoreHeader.setTextFormat(scoreFormat);
scoreText.setTextFormat(scoreFormat);
}
static function resetScore()
{
score = 0;
scoreText.text = String(score);
}
function updateTime(e:TimerEvent):void
{
trace(gameTime);
// your class variable tracking each second,
gameTime--;
//update your user interface as needed
var scoreFormat = new TextFormat("Arial Rounded MT Bold", 20, 0xFFFFFF);
timeText.defaultTextFormat = scoreFormat;
timeText.text = String(gameTime);
}
function timeExpired(e:TimerEvent):void
{
var gameTimer:Timer = e.target as Timer;
gameTimer.removeEventListener(TimerEvent.TIMER, updateTime)
gameTimer.removeEventListener(TimerEvent.TIMER, timeExpired)
// do whatever you need to do for game over
}
function moveCursor(event:Event)
{
crosshair.x=mouseX;
crosshair.y=mouseY;
}
}
}
Menu.as:
package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.ui.Mouse;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.system.LoaderContext;
import flash.display.Sprite;
import flash.net.Socket;
public class Menu extends MovieClip
{
var mainMenu:Menu = new Menu();
Main.menuLayer.addChild(myMenu);
playBtn.addEventListener(MouseEvent.CLICK, playBtnPressed);
function playBtnPressed()
{
Main.menuLayer.removeChild(myMenu);
dispatchEvent(new Event("playButtonPressed"))
}
}
My menu is a movieclip named myMenu and the class is set as Menu but I get errors such as:
Main.as, Line 50 1120: Access of undefined property playBtn
I gave the button an instance name of playBtn before I converted the menu to a movieclip so not sure what's going on there. I'm probably missing something really easy but it's a bit confusing for me after typing all day.
If you have all of your initialization stuff (including timers initializations) in Main constructor function , so you need to split it to two functions , Main constructor will show the menu , and "start" button will fire the second function , that will include all the initialization stuff