AS3 ActionScript 3 - Instantiating Objects With A Timer? - actionscript-3

I'm making a vertical (constantly) scrolling shooter & am trying to instantiate objects based on a timer. For example: At 30 seconds, place a building # x, y.
My problem is that the "building" is instantiated when the game starts and then again at the 30 second mark - instead of only # the 30 second mark.
If anyone could steer me in the correct direction, it would be greatly appreciated.
package com.gamecherry.gunslinger
{
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class ObjectPlacer extends MovieClip
{
private var Build01Timer:Timer;
private var canPlace:Boolean = true;
private var stageRef:Stage;
private var startX:Number;
private var startY:Number;
private var time:int = 5000;
public function ObjectPlacer(stageRef:Stage) : void
{
this.stageRef = stageRef;
var Build01Timer = new Timer(time, 1);
Build01Timer.addEventListener(TimerEvent.TIMER, placeTimerHandler, false, 0, true);
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
Build01Timer.start();
}
private function loop(e:Event): void
{
if (canPlace)
{
var BuildingsLeft01:BuildingsLeft = new BuildingsLeft(stage, 720, -540);
BuildingsLeft01.scaleX = -1;
stageRef.addChildAt((BuildingsLeft01), 2);
canPlace = false;
}
}
private function placeTimerHandler(e: TimerEvent) : void
{
canPlace = true;
}
private function removeSelf() : void
{
removeEventListener(Event.ENTER_FRAME, loop);
if (stageRef.contains(this))
stageRef.removeChild(this);
}
}
}
Where am I going wrong?
Thank you for looking.

Here's the first of your class:
public class ObjectPlacer extends MovieClip
{
private var Build01Timer:Timer;
**private var canPlace:Boolean = true;**
You're setting it to TRUE at the start, set it to false, and that would solve your problem :)

Related

Object Loading Issue

I am developing an application that consists of several different objects working together. Everything seems to work great, however, when I play this on a web server I notice the graphics and assets that are being loaded in from an external source are taking some time to load I'm not really sure what is going on I was hoping someone might provide some insight. Example, sometimes the graphic assets will not load at all, but audio seems to be loading in ok. Here is an example of my image loading class:
GFXReg.as
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.net.URLRequest;
import flash.display.Loader;
import flash.display.Sprite;
import flash.text.TextField;
public class GFXReg extends Sprite {
private var mc: MovieClip = new MovieClip();
private var loader: Loader = new Loader();
private var setW: Number;
public var setH: Number;
public var theH: Number;
private var bool: Boolean = false;
public function GFXReg(setSize: Boolean, W: Number, H: Number) {
bool = setSize;
if (bool) {
setW = W;
setH = H;
}
}
private function loadData(e: Event) {
if(loader.contentLoaderInfo.bytesLoaded == loader.contentLoaderInfo.bytesTotal){
addChild(loader);
}else{
var text:TextField = new TextField();
text.text = "Loading..."
addChild(text);
}
if (bool) {
loader.width = setW;
loader.height = setH;
}
}
public function theData(file: String): void {
loader.load(new URLRequest(file));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadData);
}
public function getBytes(str:String):int{
var num:int = 0;
switch(str){
case "loaded":
num = loader.contentLoaderInfo.bytesLoaded;
break;
case "total":
num = loader.contentLoaderInfo.bytesTotal;
break;
}
return num;
}
public function removeData():void{
loader.unloadAndStop(false);
trace("unload?");
}
private function unloadData(e:Event):void{
}
}
}
Main.as Sections(This loads in all the appropriate sections when prompted):
public function Main() {
xmlLoader = new XMLReg("config.xml", processXML);
}
private function processXML(e: Event): void {
theXML = new XML(e.target.data);
dir = theXML.MASTER.#DIRECTORY;
//BACKGROUND
bgGFX.theData(dir + theXML.MAINBG.#IMG);
//INITIALIZE
add(bgGFX,intro);
//INTRO WAS INSTANTIATED IN THE BEGINNING OF THIS CLASS
intro.start();
/*start method adds objects to stage, to test as a solution*/
addChildAt(header, numChildren);
//...
Also in my Main.as class I have a private method transition which loads in the appropriate sections after the previous sections have been completed these assets usually take a few seconds to load in I've noticed when working on a web server.
private function transition(e: Event): void {
//If intro is on the stage instantiate a new QuestionAnswer Object
if (intro.stage) {
header.enableMenu(true);
qa = new QuestAnswer(feedBool,nameCounter,nameVar);
qa.addEventListener("unload", transition);
qa.addEventListener("addFeed", setFeedFalse);
qa.addEventListener("addFeedTrue", setFeedTrue);
qa.addEventListener("enableHelp",enableHelp);
qa.addEventListener("getName",getName);
addChildAt(qa, numChildren-1);
remove(intro);
} else if (qa.stage) {
//If QuestionAnswer is on the Stage instantiate a new Results Object
header.enableMenu(true);
header.enableHelp(false);
results = new Results(qa.resultBundle());
results.addEventListener("unload", transition);
results.addEventListener("addFeed", setFeedFalse);
results.addEventListener("addFeedTrue", setFeedTrue);
results.addEventListener("setName",setName);
addChildAt(results, numChildren-1);
remove(qa);
} else if (results.stage) {
//If Results is on the stage loop back and instantiate a new QuestionAnswer Object
header.enableMenu(true);
header.enableHelp(false);
intro.enableAsset(true);
qa = new QuestAnswer(feedBool,nameCounter,nameVar);
qa.addEventListener("unload", transition);
qa.addEventListener("addFeed", setFeedFalse);
qa.addEventListener("addFeedTrue", setFeedTrue);
addChildAt(qa, numChildren-1);
trackAsset = true;
remove(results);
}
}

Starling not displaying graphic

Hi guys i am new to AS3 and to Starling i am having problem displaying an image in a different class. it does show on my game menu class but i wanted it to show on my play game class.
so i got 3 classes Main that starts the starling that runs GameMenu class.
"GameMenu class"
package {
import starling.display.BlendMode;
import starling.display.Button;
import starling.display.Image;
import starling.display.Sprite;
import starling.events.Event;
public class GameMenu extends Sprite {
private var bg:Image;
private var gameLogo:Image;
private var playBtn:Button;
private var rankBtn:Button;
private var settingBtn:Button;
private var inGame:PlayGame;
public function GameMenu ()
{
super ();
this.addEventListener (Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage (event:Event):void
{
this.removeEventListener (Event.ADDED_TO_STAGE, onAddedToStage);
drawScreen ();
}
private function drawScreen ():void
{
bg = new Image(Assets.getAtlas().getTexture(("Background.png")));
bg.blendMode = BlendMode.NONE;
this.addChild(bg);
gameLogo = new Image(Assets.getAtlas().getTexture(("GameLogo.png")));
gameLogo.x = stage.stageWidth/2 - gameLogo.width/2;
gameLogo.y = 30;
this.addChild(gameLogo);
playBtn = new Button(Assets.getAtlas().getTexture("PlayBtn.png"));
playBtn.x = stage.stageWidth/2 - playBtn.width/2;
playBtn.y = 450;
playBtn.addEventListener(Event.TRIGGERED, onPlayClick);
this.addChild(playBtn);
rankBtn = new Button(Assets.getAtlas().getTexture("RankBtn.png"));
rankBtn.x = rankBtn.bounds.left + 60;
rankBtn.y = 600;
rankBtn.addEventListener(Event.TRIGGERED, onRankClick);
this.addChild(rankBtn);
settingBtn = new Button(Assets.getAtlas().getTexture("SettingBtn.png"));
settingBtn.x = settingBtn.bounds.right + 60;
settingBtn.y = 600;
settingBtn.addEventListener(Event.TRIGGERED, onSettingClick);
this.addChild(settingBtn);
}
private function onRankClick (event:Event):void
{
trace("LEADERBOARD BUTTON HIT")
}
private function onSettingClick (event:Event):void
{
trace("SETTING SCREEN BUTTON HIT")
}
private function onPlayClick (event:Event):void
{
playBtn.removeEventListener(Event.TRIGGERED, onPlayClick);
trace("PLAY BUTTON HIT")
gameLogo.visible = false;
playBtn.visible = false;
rankBtn.visible = false;
settingBtn.visible = false;
//bg.visible = false;
inGame = new PlayGame();
}
}
}
this class works perfectly now.
"PlayGame class"
package {
import starling.display.Image;
import starling.display.Sprite;
import starling.events.Event;
public class PlayGame extends Sprite
{
private var bubble:Image;
public function PlayGame ()
{
trace("PlayGame");
super ();
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage2);
}
private function onAddedToStage2 (event:Event):void
{
trace("OnAddedToStage");
this.removeEventListener (Event.ADDED_TO_STAGE, onAddedToStage2);
drawScreen ();
}
public function drawScreen ():void
{
trace("Bubble");
bubble = new Image(Assets.getAtlas().getTexture(("Bubble.png")));
bubble.x = 100;
bubble.y = 100;
this.addChild(bubble);
}
}
}
the bubble image is now showing and i don't know why?
They are too much parenthesis, but this is not your issue
bubble = new Image(Assets.getAtlas().getTexture(("Bubble.png")));
//is less clean/readable than
bubble = new Image(Assets.getAtlas().getTexture("Bubble.png"));
When facing this kind of issues, if starling/air doesn't report any errors, you should try to be sure the display object are currently rendered.
Try to apply a color instead of the texture.
bubble = new Image( Texture.fromColor(64,64,0xff99ff) );
If this code shows a fancy rectangle of 64 pixel/side, you trouble come from your texture atlas or texture. Be sure to have a valided atlas, validates frames, and names.
If this code doesn't show the facy rectangle, your issue doesn't come from the texture atlas or texture, but more possibly from the display list of starling.
And in your case,
I think you should just need to addChild the Ingame in your GameMenu class :
GameMenu :
private function onPlayClick (event:Event):void
{
//... your stuff
inGame = new PlayGame();
this.parent.addChild(inGame);
}
And it should works.

How to create a Collisions var in the Back class

Edit: I have now included a Player.as and a addchild
I've been trying to understand how to do this all day and again learned a lot in doing so. But I've come to a point that i need help.
I know I have to do this: create a Collisions var in the Back1 class.
Because the background called Back1 is the movieclip that contains the Collisions image
I found a good site or 2 that does a good job of explaining variables and classes but i still don't get how i should solve this problem
Research after variables and classes:
http://www.republicofcode.com/tutorials/flash/as3variables/
http://www.photonstorm.com/archives/1136/flash-game-dev-tip-1-creating-a-cross-game-communications-structure
the above problem results in the folowing error but i believe it is caused by not creating a Collisions var in the Back1 class
ArgumentError: Error #1063: Argument count mismatch on Bumper(). expected: 2, value 0.
at flash.display::MovieClip/gotoAndStop() at
DocumentClass/onRequestStart()DocumentClass.as:64] at
flash.events::EventDispatcher/dispatchEventFunction() at
flash.events::EventDispatcher/dispatchEvent() at
MenuScreen/onClickStart()MenuScreen.as:18]
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.geom.Point;
import Bumper;
//import Back1;
public class Test extends MovieClip
{
public var leftBumping:Boolean = false;
public var rightBumping:Boolean = false;
public var upBumping:Boolean = false;
public var downBumping:Boolean = false;
public var leftBumpPoint:Point = new Point(-30,-55);
public var rightBumpPoint:Point = new Point(30,-55);
public var upBumpPoint:Point = new Point(0,-120);
public var downBumpPoint:Point = new Point(0,0);
public var scrollX:Number = 0;
public var scrollY:Number = 500;
public var xSpeed:Number = 0;
public var ySpeed:Number = 0;
public var speedConstant:Number = 4;
public var frictionConstant:Number = 0.9;
public var gravityConstant:Number = 1.8;
public var jumpConstant:Number = -35;
public var maxSpeedConstant:Number = 18;
public var doubleJumpReady:Boolean = false;
public var upReleasedInAir:Boolean = false;
public var keyCollected:Boolean = false;
public var doorOpen:Boolean = false;
public var currentLevel:int = 1;
public var animationState:String = "idle";
public var bulletList:Array = new Array();
public var enemyList:Array = new Array();
public var bumperList:Array = new Array();
public var back1:Back1;
public var collisions:Collisions;
//public var back1:Collisions = new Collisions ;
public var player:Player;
public function Test()
{
addEventListener(Event.ADDED_TO_STAGE, init);
}
public function init(e:Event):void
{
player = new Player(320, 360);
back1 = new Back1();
collisions = new Collisions();
//back1.collisions = new Collisons();
addBumpersToLevel1();
}
public function addBumpersToLevel1():void
{
addBumper(500, -115);
addBumper(740, -115);
}
public function addPlayerTolevel1():void
{
addPlayer(320, 360);
}
public function loop(e:Event):void
{
trace("back1.collisions "+back1.collisions);
trace("back1 "+back1);
trace("collisions "+collisions);
if (back1.collisions.hitTestPoint(player.x + leftBumpPoint.x,player.y + leftBumpPoint.y,true))
{
just in case i've added Bumper.as
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Bumper extends MovieClip{
public function Bumper(xLocation:int, yLocation:int) {
// constructor code
x = xLocation;
y = yLocation;
addEventListener(Event.ENTER_FRAME, bumper);
}
public function bumper(e:Event):void{
//code here
}
}
}
Player.as
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Player extends MovieClip {
public function Player(xLocation:int, yLocation:int) {
// constructor code
x = xLocation;
y = yLocation;
}
// public function removeSelf():void {
// trace("remove enemy");
// removeEventListener(Event.ENTER_FRAME, loop);
// this.parent.removeChild(this);
// }
}
}
the Back1.as file (note it's got to be instanced wrong)
package {
import flash.display.MovieClip;
public class Back1 extends MovieClip {
//public var collisions:Back1;
//what should i put here?
}
}
I am not sure I understand completely what you mean. The question is phrased strange.
I assume you want to achieve a collision between your background object (The Back class) and a player object? I can't see from the code you have posted what the player object is since there is no such variable in your Test class.
To test a collision check between two objects use the following code:
if(someObject.hitTestObject(anotherObject))
Or in your case when using hitTestPoint:
if(back1.hitTestPoint(player.x, player.y,true))
Then again I don't know from the code you have posted how the back1 class looks like. If it extends a MovieClip or Sprite and you have a Player class that does the same (OR any DisplayObject) this should work.
This:
Argument count mismatch on Bumper(). expected: 2, value 0.
The error you get seems to come from another place not shown in your code. I would assume you did not pass any parameters into the Bumper class' constructor.
Btw, is this a Flash IDE sample or some other program such as FlashDevelop or FlashBuilder? If you are using the Flash IDE and are trying to attach code to a movie clip instance placed out on the scene I don't think its possible to pass parameters to it. Sorry been a while since I've worked in the Flash IDE.
EDIT:
Here's some sample code:
//:: Change Back1 class to this
package {
import flash.display.MovieClip;
public class Back1 extends MovieClip {
public function Back1()
{
graphics.beginFill(0xFF0000);
graphics.drawRect(0, 0, 50, 50);
graphics.endFill();
}
}
}
//:: Then in your Main class (Or the Test class) add the following
var player:Player = new Player(25, 25);
var collidable:Back1 = new Back1();
addChild(player);
addChild(collidable);
//:: Goes in your loop/update
if (collidable.hitTestPoint(player.x, player.y, true))
{
trace("HIT PLAYER");
}
How you apply the graphics to the Back1 class is up to you, I just drew a simple box. It could be anything.
Set default parameters for Bumper class:
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Bumper extends MovieClip{
public function Bumper(xLocation:int = 0, yLocation:int = 0) {
// constructor code
x = xLocation;
y = yLocation;
addEventListener(Event.ENTER_FRAME, bumper);
}
public function bumper(e:Event):void{
//code here
}
}
}

Record Sound Using AS3 Worker

Hello I am trying to record the user sound using AS3 Worker everything works well when it comes to communication between the worker and the main scene but I think the record functionnality have and issue here I am using the Record Clash from bytearray.org (http://www.bytearray.org/?p=1858)
and here's is my code am I missing something :
package objects
{
import flash.events.Event;
import flash.system.MessageChannel;
import flash.system.Worker;
import flash.system.WorkerDomain;
import flash.utils.ByteArray;
import starling.display.Button;
import starling.display.Image;
import starling.display.Sprite;
import starling.events.Event;
public class RecordComponent extends Sprite
{
private var audioContainer:Image;
private var recButton:Button;
private var playButton:Button;
private var stopButton:Button;
//background thread for recording
private var worker:Worker;
private var wtm:MessageChannel;
private var mtw:MessageChannel;
private var output:ByteArray;
public function RecordComponent()
{
super();
worker = WorkerDomain.current.createWorker(Workers.RecordWorker);
wtm = worker.createMessageChannel(Worker.current);
mtw = Worker.current.createMessageChannel(worker);
worker.setSharedProperty("wtm",wtm);
worker.setSharedProperty("mtw",mtw);
worker.start();
wtm.addEventListener(flash.events.Event.CHANNEL_MESSAGE,onChannelMessage);
this.addEventListener(starling.events.Event.ADDED_TO_STAGE, onAddedToStage);
}
protected function onChannelMessage(event:flash.events.Event):void
{
output = wtm.receive();
}
protected function onAddedToStage(event:starling.events.Event):void
{
this.removeEventListener(starling.events.Event.ADDED_TO_STAGE, onAddedToStage);
drawScreen();
}
private function drawScreen():void
{
audioContainer = new Image( Assets.getAtlas().getTexture("audioContainer") );
addChild(audioContainer);
//record button
recButton = new Button( Assets.getAtlas().getTexture("recordButton") );
recButton.x=Math.ceil(194/2 - recButton.width/2);
recButton.y=5;
addChild(recButton);
//stop button
stopButton = new Button( Assets.getAtlas().getTexture("stopButton") );
stopButton.x=recButton.x+10;
stopButton.y=10;
stopButton.visible = false;
addChild(stopButton);
//play button
playButton = new Button( Assets.getAtlas().getTexture("playButton") );
playButton.x=Math.ceil(194 - playButton.width)-25;
playButton.y=10;
playButton.visible = false;
addChild(playButton);
this.addEventListener(starling.events.Event.TRIGGERED, buttons_triggeredHandler);
}
private function buttons_triggeredHandler(event:starling.events.Event):void
{
var currentButton:Button = event.target as Button;
switch(currentButton)
{
case recButton:
startRecording();
break;
case stopButton:
stopRecording();
break;
case playButton:
playRecording();
break;
}
}
private function playRecording():void
{
mtw.send("RECORD_PLAY");
}
private function stopRecording():void
{
stopButton.visible = false;
recButton.x = 25;
playButton.visible = true;
recButton.visible = true;
mtw.send("RECORD_STOP");
//
}
private function startRecording():void
{
recButton.visible = false;
stopButton.visible = true;
playButton.visible = false;
mtw.send("RECORD_START");
}
}
}
RecordWorker
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.media.Microphone;
import flash.system.MessageChannel;
import flash.system.Worker;
import org.as3wavsound.WavSound;
import org.bytearray.micrecorder.MicRecorder;
import org.bytearray.micrecorder.encoder.WaveEncoder;
import org.bytearray.micrecorder.events.RecordingEvent;
public class RecordWorker extends Sprite
{
private var wtm:MessageChannel;
private var mtw:MessageChannel;
// volume in the final WAV file will be downsampled to 50%
private var volume:Number = .75;
// we create the WAV encoder to be used by MicRecorder
private var wavEncoder:WaveEncoder = new WaveEncoder( volume );
// we create the MicRecorder object which does the job
private var recorder:MicRecorder = new MicRecorder( wavEncoder,Microphone.getEnhancedMicrophone() );
public function RecordWorker()
{
wtm = Worker.current.getSharedProperty("wtm");
mtw = Worker.current.getSharedProperty("mtw");
mtw.addEventListener(Event.CHANNEL_MESSAGE,command_Handler);
}
//message received from the main component
protected function command_Handler(event:Event):void
{
switch(mtw.receive())
{
case "RECORD_START":
trace("recording.....");
recorder.record();
recorder.addEventListener(RecordingEvent.RECORDING, onRecording);
recorder.addEventListener(flash.events.Event.COMPLETE, onRecordComplete);
break;
case "RECORD_STOP":
trace("record stopped....");
recorder.stop();
break;
case "RECORD_PLAY":
if(recorder.output.length>0)
{
var player:WavSound = new WavSound(recorder.output);
player.play();
}
break;
}
}
private function onRecording(event:RecordingEvent):void
{
trace ( event.time );
}
private function onRecordComplete(event:flash.events.Event):void
{
}
}
}
anny help will be appriciated
Thanks,
Khaled
Looking at this write-up on Adobe's AS3 reference, it seems that because each created worker is "a virtual instance of the Flash runtime", it has no direct connection to any of the core runtime's input or output channels. The Microphone class is one such cut-off interface, which is why it can't reach the system mic inside a worker.

About class(es) in ActionScript

I have one folder(Projects), which contains 2 files: FirstPro.fla, FirstClass.as
The goal of my question is interaction with two different objects (MovieClip) from class, which i created by myself, i have only one class, and it class for only one MovieClip, my goal is interaction, for MovieClip second which has name(letterPanel) has no class, its only MovieClip on scene;
In FirstClass.as i have the next code:
package
{
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Stage;
public class FirstClass extends MovieClip
{
public function FirstClass()
{
var NewMyTimer:Timer = new Timer(100);
NewMyTimer.addEventListener(TimerEvent.TIMER, hm);
NewMyTimer.start();
}
public function hm(TimerEvent):void
{
this.y += 5;
if(this.hitTestObject(letterPanel))
{
trace("Coincidens");
}
}
}
}
And in FirstPro.fla file i have on the scene i have two MovieClip (Images), one of them has firstobj name, which has link with my created class, and it works, my object firstobj going down with the timer, but i would like to interaction with the second object(MovieClip-letterPanel) - if(this.hitTestObject(letterPanel)) { trace("Coincidens"); }
If i write this code in my class this output mistake (letterPanel) is not undefined, what can i do with interactions of those two object in one class,?
You have to assign the MovieClip and you also can not start the timer untill that var has been set
package{
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Stage;
public class FirstClass extends MovieClip{
private var _letterPanel:MovieClip;
public function FirstClass(){
}
public function startConter( ):void{
var NewMyTimer:Timer=new Timer(100);
NewMyTimer.addEventListener(TimerEvent.TIMER, hm);
NewMyTimer.start();
}
public function hm(TimerEvent):void{
this.y+=5;
if(this.hitTestObject(this._letterPanel)){
trace("Coincidens");
}
}
public function set letterPanel( val:MovieClip ):void{
this._letterPanel = val;
}
}
}
var firstClass:FirstClass = new FirstClass( );
firstClass.letterPanel = letterPanel;
firstClass.startCounter( );
My initial response(other than being confused, since your explaination of your project is a bit hard to understand) is that you don't have a good grasp on OOP. There was an answer for this question before that I believed to be correct. If I remember correctly you rejected it simply because it didn't utilize classes. OOP is about knowing how to as well as when to implement OOP concepts such as abstraction, encapsulation, inheritance, polymorphism etc.
In your case I think the simple answer to your question is the following:
stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onEnterFrame(e:Event):void
{
if(displayObject1.hitTestObject(displayObject2)
trace("hit");
}// end function
However if you feel the need to truely use classes, I've created a similar flash application to demonstrate how you would go about it. Its basically 3 draggable red, green and blue circle display objects on the stage and when you drag a circle display object and it overlaps/intersects another circle display object a trace is made to describe the collision. You can run the application by simply copying and pasting the following code into your document class:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}// end function
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var redCircle:Circle = new Circle(Color.RED, 50);
redCircle.name = "redCircle";
redCircle.x = 100;
redCircle.y = 100;
addChild(redCircle);
var greenCircle:Circle = new Circle(Color.GREEN, 50);
greenCircle.name = "greenCircle";
greenCircle.x = 300;
greenCircle.y = 100;
addChild(greenCircle);
var blueCircle:Circle = new Circle(Color.BLUE, 50);
blueCircle.name = "blueCircle";
blueCircle.x = 500;
blueCircle.y = 100;
addChild(blueCircle);
var collision:Collision = new Collision(stage, redCircle, greenCircle, blueCircle);
collision.addEventListener(CollisionEvent.COLLISION, onCollision);
}// end function
private function onCollision(e:CollisionEvent):void
{
var collision:Collision = Collision(e.target);
collision.removeEventListener(CollisionEvent.COLLISION, onCollision);
trace("There was a collision between " + e.displayObject1.name + " and " + e.displayObject2.name);
}// end function
}// end class
}// end package
internal class Color
{
public static const RED:uint = 0xFF0000;
public static const GREEN:uint = 0x00FF00;
public static const BLUE:uint = 0x0000FF;
}// end class
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.EventDispatcher;
import flash.events.Event;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
internal class Circle extends Sprite
{
public function Circle(color:uint, radius:Number)
{
graphics.beginFill(color);
graphics.drawCircle(0,0,radius);
graphics.endFill();
addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
}// end function
private function onMouseDown(e:MouseEvent):void
{
parent.setChildIndex(this, parent.numChildren - 1);
startDrag();
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp)
}// end function
private function onMouseUp(e:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
stopDrag();
}// end function
}// end class
internal class Collision extends EventDispatcher
{
private var _stage:Stage;
private var _doVector:Vector.<DisplayObject>;
public function Collision(stage:Stage, ...displayObjects)
{
_stage = stage;
_doVector = getDOVector(validateArgs(displayObjects, DisplayObject));
init();
}// end function
private function init():void
{
_stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
}// end function
private function onEnterFrame(e:Event):void
{
for(var i:uint = 0; i < _doVector.length; i++)
{
for(var j:uint = 0; j < _doVector.length; j++)
{
if (_doVector[i] != _doVector[j])
{
if (_doVector[i].hitTestObject(_doVector[j]))
dispatchEvent(new CollisionEvent(CollisionEvent.COLLISION, _doVector[i], _doVector[j]));
}// end if
} // end for
}// end for
}// end function
private function validateArgs(args:Array, type:Class):Array
{
for each(var arg:* in args)
if(!(arg is type))
throw new ArgumentError("Argument must be of type " + type);
return args;
}// end function
private function getDOVector(array:Array):Vector.<DisplayObject>
{
var doVector:Vector.<DisplayObject> = new Vector.<DisplayObject>();
for each(var displayObject:DisplayObject in array)
doVector.push(displayObject);
return doVector;
}// end function
}// end class
internal class CollisionEvent extends Event
{
public static const COLLISION:String = "collision";
private var _displayObject1:DisplayObject;
private var _displayObject2:DisplayObject;
public function get displayObject1():DisplayObject { return _displayObject1 };
public function get displayObject2():DisplayObject { return _displayObject2 };
public function CollisionEvent(type:String,
displayObject1:DisplayObject,
displayObject2:DisplayObject,
bubbles:Boolean = false,
cancelable:Boolean = false):void
{
_displayObject1 = displayObject1;
_displayObject2 = displayObject2;
super(type, bubbles, cancelable);
}// end function
override public function clone():Event
{
return new CollisionEvent(type, displayObject1, displayObject2, bubbles, cancelable);
}// end function
}// end class