adding a object to another object in as3 - actionscript-3

Ok so i have a character on the screen and when it moves the camera follows(thanks to manifest222 on youtube) i have a wall where the player cant go through. I also have boxes adding to the stage but i want it so that the box adds to onto another object hers the code.
package {
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.display.Stage;
public class Main extends MovieClip {
// player
public var characterEndMC:MovieClip = new charEndMC();
public var arrayOfBarrier:Array = new Array();
//box
private var boxAmount:Number=0;
private var boxLimit:Number=20;
private var _root:Object;
//$txt
public var money:int=0;
public var gold:int=0;
public var my_scrollbar:MakeScrollBar;
//$$
public var testnumber:Number=1;
//enemy1
private var e01Amount:Number=0;
private var e01Limit:Number=2;
public function Main() {
$box.click$.move$.buttonMode=true;
$box.click$.clickmini$.buttonMode=true;
backgroundpic.visible = false;
character_mc["charAngle"]=0;
character_mc["moveX"]=0;
character_mc["moveY"]=0;
character_mc["walkSpeed"]=5;
stage.addEventListener(MouseEvent.CLICK, charMove);
//box add listener
addEventListener(Event.ENTER_FRAME, eFrame);
//moneybox
$box.click$.move$.addEventListener(MouseEvent.MOUSE_DOWN, startmoving$);
$box.click$.move$.addEventListener(MouseEvent.MOUSE_UP, stopmoving$);
$box.click$.clickmini$.addEventListener(MouseEvent.CLICK, c$mini);
my_scrollbar=new MakeScrollBar(scroll_mc,scroll_text);
}
public function charLoop(event:Event) {
if (character_mc.hitTestPoint(character_mc["charEnd"].x,character_mc["charEnd"].y,true)) {
character_mc["moveX"]=0;
character_mc["moveY"]=0;
this.removeChild(character_mc["charEnd"]);
character_mc.removeEventListener(Event.ENTER_FRAME, charLoop);
}
for (var j:int = 0; j < arrayOfBarrier.length; j++) {
if (character_mc.hitTestObject(arrayOfBarrier[j])) {
character_mc.x-=character_mc["moveX"];
character_mc.y-=character_mc["moveY"];
character_mc["moveX"]=0;
character_mc["moveY"]=0;
this.removeChild(character_mc["charEnd"]);
character_mc.removeEventListener(Event.ENTER_FRAME, charLoop);
}
}
for (var i:int = 0; i < this.numChildren; i++) {
this.getChildAt(i).x-=character_mc["moveX"];
this.getChildAt(i).y-=character_mc["moveY"];
}
character_mc.x+=character_mc["moveX"]+.05;
character_mc.y+=character_mc["moveY"]+.05;
}
public function lookAtMouse() {
var characterMC:MovieClip=character_mc;
characterMC["charAngle"] = Math.atan2(this.mouseY - characterMC.y, this.mouseX - characterMC.x) / (Math.PI / 180);
characterMC.rotation=characterMC["charAngle"];
}
public function charMove(event:MouseEvent) {
lookAtMouse();
this.addChild(characterEndMC);
characterEndMC.x=this.mouseX;
characterEndMC.y=this.mouseY;
character_mc["charEnd"]=characterEndMC;
character_mc["charEnd"].visible = false;
character_mc["moveX"]=Math.cos(character_mc["charAngle"]*Math.PI/180)*character_mc["walkSpeed"];
character_mc["moveY"]=Math.sin(character_mc["charAngle"]*Math.PI/180)*character_mc["walkSpeed"];
character_mc.addEventListener(Event.ENTER_FRAME, charLoop);
}
//boxadding
private function eFrame(event:Event):void {
if (boxAmount<boxLimit) {
boxAmount++;
var _box:Box=new Box ;
_box.addEventListener(MouseEvent.CLICK,boxclick);
_box.buttonMode=true;
_box.y=Math.random()* backgroundpic.height;
_box.x=Math.random()* backgroundpic.width;
addChild(_box);
}
if (e01Amount<e01Limit) {
e01Amount++;
var Enemy1: enemy01=new enemy01 ;
Enemy1.addEventListener(MouseEvent.CLICK, en01click);
Enemy1.buttonMode=true;
Enemy1.y=Math.random()*stage.stageHeight;
Enemy1.x=Math.random()*stage.stageWidth;
addChild(Enemy1);
}
}
public function boxclick(event:MouseEvent):void {
var _box:Box=event.currentTarget as Box;
logtxt.appendText("You collected " + testnumber + " boxes" + "\n" );
character_mc["moveX"] = _box.y + 40 + (character_mc.height / 2);
character_mc["moveY"]=_box.x;
logtxt.scrollV=logtxt.maxScrollV;
var randVal$:Number=Math.random();
if (randVal$>=0.49) {
money+=100;
} else if (randVal$ <= 0.50 && randVal$ >= 0.15) {
money+=200;
} else if (randVal$ <= 0.14 && randVal$ >= 0.02) {
gold+=10;
} else if (randVal$ == 0.01) {
money+=200;
gold+=20;
}
testnumber++;
boxAmount--;
$box.box$in.box$insins.Moneytxt.text=String(money);
$box.box$in.box$insins.Goldtxt.text=String(gold);
removeChild(_box);
}
private function startmoving$(event:MouseEvent):void {
$box.startDrag();
}
private function stopmoving$(event:MouseEvent):void {
$box.stopDrag();
}
private function c$mini(event:MouseEvent):void {
$box.click$.move$.visible=false;
$box.box$in.visible=false;
$box.y=200;
$box.x=100;
$box.click$.clickmini$.addEventListener(MouseEvent.CLICK, reclickbox$);
$box.click$.clickmini$.removeEventListener(MouseEvent.CLICK, c$mini);
}
private function reclickbox$(event:MouseEvent):void {
$box.click$.clickmini$.addEventListener(MouseEvent.CLICK, c$mini);
$box.click$.clickmini$.removeEventListener(MouseEvent.CLICK, reclickbox$);
$box.y=70;
$box.x=250;
$box.click$.move$.visible=true;
$box.box$in.visible=true;
}
public function scroll_text( n:Number ) {
logtxt.scrollV = Math.round( ( logtxt.maxScrollV - 1 ) * n ) + 1;
}
public function en01click (event:MouseEvent){
}
}
}

That's:
var _box:Box = new Box();
receivingDisplayObjectInstanceName.addChild(_box);

Related

Flash, AS3: Dynamic MovieClips won't show if link them to as3 custom class

I'm writing a little flash game, and i have faced a problem adding MovieClips to stage.
I have function createBricks(), which is adding MovieClips to stage. If i do it like this:
public function createBricks():void
{
for (var i:int = 0; i < amountOfBricks; i++)
{
var brick:MovieClip = new brick2();
brick.x = i * brick.width + 10;
brick.y = 6;
addChild(brick);
}
}
Everything is okay, i can see bricks on stage. But the problem is I need to have some logic in Brick class.
So if I do it like this:
public function createBricks():void
{
for (var i:int = 0; i < amountOfBricks; i++)
{
var brick:MovieClip = new Brick(this);
brick.x = i * brick.width + 10;
brick.y = 6;
addChild(brick);
}
}
I can't see MovieClips on stage.
Any help is appreciated.
class Brick code:
package
{
import flash.display.MovieClip;
import flash.events.Event;
import Arkanoid;
public class Brick extends MovieClip
{
private var mParent:MovieClip;
public function Brick(parent:Arkanoid)
{
this.mParent = parent;
super();
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
private function enterFrameHandler(event:Event):void
{
if (this.hitTestObject(mParent.view.ball))
{
mParent.ballYSpeed *= -1;
mParent.removeChild(this);
removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
}
}
}
game class:
package
{
import flash.display.MovieClip;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.MouseEvent
import flash.events.Event;
import Brick;
public class Arkanoid extends MovieClip
{
private var mView:MovieClip;
private var paddle:MovieClip;
private var ball:MovieClip;
private var amountOfBricks:int = 6;
private var ballXSpeed:int = 10;
private var ballYSpeed:int = 10;
public function Arkanoid()
{
mView = new GameView();
paddle = mView.paddle;
ball = mView.ball;
super();
}
public function start():void
{
addListeners();
paddle.x = 100;
createBricks();
addChild(mView);
}
public function addListeners():void
{
mView.addEventListener(MouseEvent.MOUSE_MOVE, paddle_mouseMoveHandler);
mView.addEventListener(Event.ENTER_FRAME, ball_enterFrameHandler);
}
private function paddle_mouseMoveHandler(event:MouseEvent):void
{
paddle.x = mouseX - paddle.width / 2;
if (mouseX < paddle.width / 2)
{
paddle.x = 0;
}
if (mouseX > mView.width - paddle.width / 2)
{
paddle.x = mView.width - paddle.width;
}
}
private function ball_enterFrameHandler(event:Event):void
{
ball.x += ballXSpeed;
ball.y += ballYSpeed;
if (ball.x >= mView.width - ball.width)
{
ballXSpeed *= -1;
}
if (ball.x <= 0)
{
ballXSpeed *= -1;
}
if (ball.y >= mView.height - ball.height)
{
ballYSpeed *= -1;
}
if (ball.y <= 0)
{
ballYSpeed *= -1;
}
if (ball.hitTestObject(paddle))
{
calculateBallAngle();
}
}
private function calculateBallAngle():void
{
var ballPosition:Number = ball.x - paddle.x;
var hitPercent:Number = (ballPosition / (paddle.width - ball.width)) - .5;
ballXSpeed = hitPercent * 10;
ballYSpeed = - 1;
}
public function createBricks():void
{
for (var i:int = 0; i < amountOfBricks; i++)
{
//var brick:MovieClip = new brick2();
var brick:MovieClip = new Brick(this);
brick.x = i * brick.width + 10;
brick.y = 6;
addChild(brick);
}
}
public function get view():MovieClip
{
return mView;
}
}
}
1| Create class called Brick
class Brick extends MovieClip {
var ground;
public function Brick(_ground){
ground = _ground;
var brickSample:MovieClip = new brick2();
addChild(brickSample);
}
}
2| Now you can create your movieclips like you want
public function createBricks():void
{
for (var i:int = 0; i < amountOfBricks; i++)
{
var brick:MovieClip = new Brick(this);
brick.x = i * brick.width + 10;
brick.y = 6
addChild(brick);
}
}
hope it helps

Does bitmapdata.copyPixels reduce image quality?

I am using a pair of classes to process and use Sprite Sheets but i have a slight problem, in comparison to the Bitmap class my SpriteSheetClips look very ugly, I scale both, Bitmap and SpriteSheetClip up and down using exactly the same image loaded and they look very different Bitmap looks smooth and nice while my SpriteSheetClips look pixelated with white borders, what is wrong with my classes that is causing this problem?
SpriteSheet (contains the cut bitmapDatas to be used for the clip):
package src {
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.geom.Point;
public class SpriteSheet {
private var frames:Array = new Array();
public function SpriteSheet(spriteSheet:BitmapData, spriteSheetXML:XML)
{
var tileAmount:int = spriteSheetXML.SubTexture.length();
var rect:Rectangle;
var point:Point = new Point(0, 0);
var frame:BitmapData;
for (var a:int = 0; a < tileAmount ; a++)
{
frame = new BitmapData(spriteSheetXML.SubTexture[a].#width, spriteSheetXML.SubTexture[a].#height);
rect = new Rectangle(spriteSheetXML.SubTexture[a].#x, spriteSheetXML.SubTexture[a].#y, spriteSheetXML.SubTexture[a].#width, spriteSheetXML.SubTexture[a].#height);
frame.copyPixels(spriteSheet, rect, point);
frames.push(frame);
}
}
public function getTile(tileNum:int):BitmapData
{
return frames[tileNum-1];
}
public function get length():int
{
return frames.length;
}
}
}
SpriteSheetClip:
package src {
import flash.display.Sprite;
import flash.display.Bitmap;
import flash.events.Event;
public class SpriteSheetClip extends Sprite{
private var spriteSheet:SpriteSheet;
public var frame:Bitmap;
private var _currentFrame:int = 1;
private var _isPlaying:Boolean = true;
public var isLooping:Boolean = true;
private var frames:Array = new Array();
public function SpriteSheetClip(spriteSheetUsed:SpriteSheet)
{
spriteSheet = spriteSheetUsed;
frame = new Bitmap(spriteSheet.getTile(1), "auto", true);
this.addChild(frame);
for (var a:int = 0; a < totalFrames; a++)
{
frames.push({labelName:"", action:""});
}
this.addEventListener(Event.ENTER_FRAME, onFrameLoop, false, 0, true);
}
public function get currentFrame():int
{
return _currentFrame;
}
public function get totalFrames():int
{
return spriteSheet.length;
}
public function get isPlaying():Boolean
{
return _isPlaying;
}
public function start()
{
_isPlaying = true;
}
public function stop()
{
_isPlaying = false;
}
public function addFrameLabel(frameNum:int, labelName:String)
{
if (frameNum == 0)
{
return;
}
frames[frameNum-1].frameLabel = labelName;
}
public function addConnection(frameLabel:*, connectedFrameLabel:*)
{
var frameNum:int = frameNumber(frameLabel);
if (frameNum == 0)
{
return;
}
frames[frameNum-1].action = connectedFrameLabel;
}
private function frameNumber(frameLabel:*):int
{
if (int(frameLabel) <= totalFrames && int(frameLabel) > 0)
{
return int(frameLabel);
}
for (var a:int = 0; a < frames.length; a++)
{
if (frames[a].frameLabel == frameLabel)
{
return (a+1);
}
}
return 0;
}
public function gotoAndStop(frameLabel:*)
{
var frameNum:int = frameNumber(frameLabel);
if (frameNum > 0 && frameNum <= totalFrames)
{
_currentFrame = frameNum;
}
updateFrame();
stop();
}
public function gotoAndPlay(frameLabel:*)
{
var frameNum:int = frameNumber(frameLabel);
if (frameNum > 0 && frameNum <= totalFrames)
{
_currentFrame = frameNum;
}
updateFrame();
start();
}
private function updateFrame()
{
frame.bitmapData = spriteSheet.getTile(currentFrame);
}
public function nextFrame()
{
frame.bitmapData = spriteSheet.getTile(currentFrame);
if (frames[currentFrame-1].action != "")
{
this.gotoAndPlay(frames[currentFrame-1].action);
return;
}
_currentFrame++;
if (currentFrame > totalFrames)
{
if (isLooping)
{
_currentFrame = 1;
}
else
{
_currentFrame = totalFrames;
_isPlaying = false;
}
}
}
private function onFrameLoop(e:Event)
{
if (isPlaying)
{
nextFrame();
}
}
}
}

Actionscript 3.0 - MouseEvents not working

I'm trying to code a sort of strategy game through FlashDevelop and I'm getting problems when trying to use Events (particularly MouseEvents). It's not so much that the events are returning errors, it's just that they don't do anything, not even getting a trace.
I'm trying to make the hexagons HexObject image invisible when clicked on (just a simple test to see if the MouseEvent is actually working).
This is my code:
Main.as
package {
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
/**
* ...
* #author Dean Sinclair
*/
public class Main extends Sprite {
public var gameInitialised:Boolean = false;
public var MIN_X:int = 0;
public var MAX_X:int = stage.stageWidth;
public var MIN_Y:int = 0;
public var MAX_Y:int = stage.stageHeight - 100;
public var GameGrid:HexGrid = new HexGrid(MIN_X, MAX_X, MIN_Y, MAX_Y);
public var blackBG:Shape = new Shape();
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);
addEventListener(Event.ENTER_FRAME, update);
// entry point
}
private function update(event:Event):void {
if (gameInitialised == false) {
GameGrid.initialiseGrid();
initialiseBackground();
gameInitialised = true;
}
updateGraphics();
}
public function drawGrid():void {
for (var x:int = 0; x < GameGrid.TOTAL_X; x++) {
for (var y:int = GameGrid.yArray[x][0]; y < GameGrid.yArray[x][1]; y++) {
if (x != GameGrid.nox || y != GameGrid.noy) {
GameGrid.Grid[x][y].update();
this.stage.addChild(GameGrid.Grid[x][y].image);
}
}
}
}
public function updateGraphics():void {
this.stage.addChild(blackBG);
drawGrid();
}
public function initialiseBackground():void {
blackBG.graphics.beginFill(0x000000, 1);
blackBG.graphics.lineStyle(10, 0xffffff, 1);
blackBG.graphics.drawRect(0, 0, stage.stageWidth-1, stage.stageHeight-1);
blackBG.graphics.endFill();
}
}
}
HexGrid.as
package {
import flash.display.Sprite;
import flash.events.Event;
/**
* ...
* #author Dean Sinclair
*/
public class HexGrid extends Sprite {
public static var HEX_RADIUS:int = 0;
public static var HEX_DIAMETER:int = 0;
public static var GRID_WIDTH:int = 0;
public static var GRID_HEIGHT:int = 0;
public var TOTAL_X:int = 0;
public var MIN_X:int = 0;
public var MAX_X:int = 0;
public var MIN_Y:int = 0;
public var MAX_Y:int = 0;
public var Grid:Array;
public var yArray:Array;
public function HexGrid(min_x:int, max_x:int, min_y:int, max_y:int) {
super();
MIN_X = min_x;
MAX_X = max_x;
MIN_Y = min_y;
MAX_Y = max_y;
}
public function initialiseGrid():void {
setGridDetails();
setLineLengths();
setGridPositions();
}
public function setGridDetails():void {
HEX_RADIUS = 25;
HEX_DIAMETER = 2 * HEX_RADIUS;
GRID_WIDTH = (((MAX_X - MIN_X) / HEX_DIAMETER) - 1);
GRID_HEIGHT = ((((MAX_Y - 100) - MIN_Y) / (HEX_DIAMETER - (HEX_DIAMETER / 3))) - 3);
TOTAL_X = GRID_WIDTH + Math.floor((GRID_HEIGHT - 1) / 2);
}
private function setLineLengths():void {
yArray = new Array(TOTAL_X);
for (var a:int = 0; a < TOTAL_X; a++) {
yArray[a] = new Array(2);
}
for (var x:int = 0; x < TOTAL_X; x++) {
if (x < GRID_WIDTH) {
yArray[x][0] = 0;
}else {
yArray[x][0] = (x - GRID_WIDTH + 1) * 2;
}
yArray[x][1] = 1 + (2 * x);
if (yArray[x][1] > GRID_HEIGHT) {
yArray[x][1] = GRID_HEIGHT;
}
trace("Line", x, " starts at", yArray[x][0], " ends at", yArray[x][1]);
}
}
public var nox:int = 5;
public var noy:int = 3;
private function setGridPositions():void {
var hexState:int = 4;
Grid = new Array(TOTAL_X);
for (var x:int = 0; x < TOTAL_X; x++) {
Grid[x] = new Array(yArray[x][1]);
for (var y:int = yArray[x][0]; y < yArray[x][1]; y++) {
if(nox!=4 || noy!=6){
Grid[x][y] = new HexObject(HEX_DIAMETER + (HEX_DIAMETER * x) - (HEX_RADIUS * y), HEX_DIAMETER + (HEX_DIAMETER * y) - ((HEX_DIAMETER / 3) * y), HEX_RADIUS, 2);
}
}
}
}
}
}
HexObject.as
package {
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
/**
* ...
* #author Dean Sinclair
*/
public class HexObject extends Sprite {
[Embed(source = "../images/hexagons/hex_darkRed.png")]
private var DarkRedHex:Class;
[Embed(source = "../images/hexagons/hex_lightBlue.png")]
private var LightBlueHex:Class;
[Embed(source = "../images/hexagons/hex_midGreen.png")]
private var MidGreenHex:Class;
public var image:Bitmap = new LightBlueHex();
protected var state:int = 0;
private var radius:int = 0;
public function HexObject(xPos:int, yPos:int, hexRadius:int, hexState:int) {
super();
x = xPos;
y = yPos;
state = hexState;
radius = hexRadius;
checkState();
initialiseGraphics();
}
private function checkState():void {
switch(state) {
case 1: // plains
image = new MidGreenHex();
break;
case 2: // hills
break;
case 3: // rock
image = new DarkRedHex();
break;
case 4: // water
image = new LightBlueHex();
break;
default:
break;
}
}
private function initialiseGraphics():void {
image.visible = true;
image.width = radius * 2;
image.height = radius * 2;
image.x = x - radius;
image.y = y - radius;
}
private function onMouseClick(e:MouseEvent):void {
image.visible = false;
trace("image.visible =", image.visible);
}
public function update():void {
image.addEventListener(MouseEvent.CLICK, onMouseClick);
}
}
}
I've tried countless methods to get the events working, but none have had any success. Any sort of solution to this would be a lifesaver as I've been toiling over this for hours, thanks!
My problem was fixed by VBCPP, I was using the class Bitmap which cannot dispatch MouseEvents. The solution was to take image from HexObject and put it inside an container of type Sprite, with the logical one being the object it was in. I just had to add the following code inside HexObject.as:
this.addChild(image);
and then just refer to the Object in future as opposed to image.

FLEX - BitmapImage not updated after filters assigned

I've a flex mobile project and a component (as-Class) inside of it with an BitmapImage, a Button and a Graphic sign.
When a boolean is false the button is disabled, the image gets gray through a ColorMatrixFilter (bitmapImage.filters = [myCMFilter]) and the sign appers, else button is enabled, the image has no filters (bitmapImage.filters = []).
The problem is that the image doesn't switch to grey -> but the sign appears and the button gets disabled.
If call the setting of the filters one frame later (callLater -> a function setting the filters) everything works.
I have extracted the code to a sample project and everything works... without callLater
Anyone an idea what can happpen in my case???
Christian
Code:
package de.xxx.yyy.app.view.componentsV2.widgets
{
import de.assets.header.HeaderBGDarkGray;
import de.assets.miscellaneous.StarGrey;
import de.assets.miscellaneous.StarYellow;
import de.assets.miscellaneous.UnderConstruction;
import de.assets.ImageAssets;
import de.xxx.yyy.app.view.componentsV2.buttons.BasicButton;
import de.xxx.yyy.app.view.pools.UserInterfaceComponentsPool;
import flash.debugger.enterDebugger;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.ColorMatrixFilter;
import mx.core.IVisualElement;
import mx.core.UIComponent;
import spark.components.Button;
import spark.components.Group;
import spark.core.SpriteVisualElement;
import spark.primitives.BitmapImage;
public class StadiumWidget extends Group{
private static var STADION_LEVELS:int = 7;
private static var SIDE_SPACING:int = 7;
private static var BUTTON_WIDTH:int = 150;
private static var BUTTON_HEIGHT:int = 33;
////////////////////////////////////////////////////////////////////////////
// USER INTERFACE COMPONENTS
////////////////////////////////////////////////////////////////////////////
private var underConstructionImage:UnderConstruction;
private var currentImage:BitmapImage;
private var footerBackground:HeaderBGDarkGray;
private var developButton:BasicButton;
private var manageButton:BasicButton;
private var displayedlevel:int;
////////////////////////////////////////////////////////////////////////////
// FIELDS
////////////////////////////////////////////////////////////////////////////
private var createdStars:Array = [];
////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////
private var _grayscaleFilter:ColorMatrixFilter;
public function get grayscaleFilter():ColorMatrixFilter
{
if(!_grayscaleFilter)
{
var matrix:Array = [0.3, 0.59, 0.11, 0, 0,
0.3, 0.59, 0.11, 0, 0,
0.3, 0.59, 0.11, 0, 0,
0, 0, 0, 1, 0];
_grayscaleFilter = new ColorMatrixFilter(matrix);
}
return _grayscaleFilter;
}
public function set grayscaleFilter(value:ColorMatrixFilter):void
{
_grayscaleFilter = value;
}
////////////////////////////////////////////////////////////////////////////
// GETTER AND SETTER WITH DIRTY FLAG
////////////////////////////////////////////////////////////////////////////
private var levelChanged:Boolean;
private var _level:int;
public function set level(value:int):void
{
_level = value;
levelChanged = true;
invalidateProperties();
invalidateDisplayList()
}
public function get level():int
{
return _level;
}
//
private var isUnderConstructionChanged:Boolean;
private var _isUnderConstruction:Boolean;
public function set isUnderConstruction(value:Boolean):void
{
_isUnderConstruction = value;
isUnderConstructionChanged = true;
invalidateProperties();
invalidateDisplayList()
}
public function get isUnderConstruction():Boolean
{
return _isUnderConstruction;
}
////////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
////////////////////////////////////////////////////////////////////////////
public function Stadium()
{
super();
}
////////////////////////////////////////////////////////////////////////////
// LIFECYCLE STANDARD METHODS
////////////////////////////////////////////////////////////////////////////
var testSprite:UIComponent;
override protected function createChildren():void
{
super.createChildren();
currentImage = new BitmapImage();
currentImage.smooth = true;
currentImage.percentWidth = 100;
currentImage.scaleMode = "letterbox";
addElement(currentImage);
// FOOTER
footerBackground = new HeaderBGDarkGray();
addElement(footerBackground);
developButton = new BasicButton();
developButton.width = BUTTON_WIDTH;
developButton.height = 38;
developButton.x = SIDE_SPACING;
developButton.label = resourceManager.getString("FlexApp", "stadium.developButtonLabel");
developButton.addEventListener(MouseEvent.CLICK, handleDevelopButtonClicked);
addElement(developButton);
manageButton = new BasicButton();
manageButton.width = BUTTON_WIDTH;
manageButton.height = 38;
manageButton.label = resourceManager.getString("FlexApp", "stadium.manageButtonLabel");
manageButton.addEventListener(MouseEvent.CLICK, handleManageButtonClicked);
addElement(manageButton);
}
override protected function commitProperties():void
{
super.commitProperties();
if(currentImage && levelChanged)
{
setcurrentImage();
setStars();
levelChanged = false;
}
if(isUnderConstructionChanged)
{
setUnderConstruction();
isUnderConstructionChanged = false;
}
}
override protected function measure():void
{
super.measure();
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
var FOOTER_HEIGHT:int = footerBackground.getPreferredBoundsHeight();
var STAR_X_STEP:int = 25;
footerBackground.y = unscaledHeight - FOOTER_HEIGHT;
footerBackground.width = unscaledWidth;
manageButton.x = unscaledWidth - (BUTTON_WIDTH + SIDE_SPACING);
manageButton.y = developButton.y = footerBackground.y + ((FOOTER_HEIGHT - BUTTON_HEIGHT) / 2);
if(currentImage.height > unscaledHeight - footerBackground.height)
{
currentImage.height = unscaledHeight - footerBackground.height;
}
if(underConstructionImage)
{
underConstructionImage.x = (unscaledWidth - underConstructionImage.width) / 2;
}
var starStartX:int = unscaledWidth / 2 - (STADION_LEVELS * STAR_X_STEP) / 2;
var starY:int = createdStars.length > 0 ? unscaledHeight - FOOTER_HEIGHT + (FOOTER_HEIGHT - createdStars[0].height) / 2 : 0;
for(var i:int = 0; i < createdStars.length; i++)
{
createdStars[i].y = starY;
createdStars[i].x = starStartX + i * STAR_X_STEP;
}
}
////////////////////////////////////////////////////////////////////////////
// HELPER METHODS
////////////////////////////////////////////////////////////////////////////
private function setStars():void
{
var pool:UserInterfaceComponentsPool = UserInterfaceComponentsPool.getInstance();
var star:IVisualElement;
while(createdStars.length > 0)
{
star = createdStars.pop() as IVisualElement;
if(containsElement(star))
{
removeElement(star);
}
pool.disposeUserInterfaceComponent(star);
}
// POOL THE STARS!!!
for(var i:int = 1; i <= STADION_LEVELS; i++)
{
if(i <= level)
{
star = pool.getYellowStar();
}
else
{
star = pool.getGreyStar();
}
addElement(star)
createdStars.push(star);
}
}
private function setcurrentImage():void
{
if(level != displayedlevel)
{
currentImage.source = currentImages["LEVEL_" + level + "_NAME"];
displayedlevel = level;
}
setUnderConstruction();
}
private function setUnderConstruction():void
{
developButton.enabled = isUnderConstruction == false;
if(isUnderConstruction)
{
if(!underConstructionImage)
{
underConstructionImage = new UnderConstruction();
underConstructionImage.y = 30;
underConstructionImage.width = 330;
underConstructionImage.height = 330;
addElement(underConstructionImage);
}
callLater(setFilters, [true]);
}
else
{
callLater(setFilters, [false]);
if(underConstructionImage && containsElement(underConstructionImage))
{
removeElement(underConstructionImage);
}
underConstructionImage = null;
}
}
private function setFilters(value:Boolean):void
{
if(value && (!currentImage.filters || currentImage.filters.length == 0))
{
currentImage.filters = [grayscaleFilter];
}
else if(!value && currentImage.filters && currentImage.filters.length > 0)
{
currentImage.filters = [];
}
}
////////////////////////////////////////////////////////////////////////////
// EVENT HANDLER
////////////////////////////////////////////////////////////////////////////
private function handleDevelopButtonClicked(event:MouseEvent):void
{
dispatchEvent(new Event("openlevelPopup", true));
}
private function handleManageButtonClicked(event:MouseEvent):void
{
dispatchEvent(new Event("openManagePopup", true));
}
////////////////////////////////////////////////////////////////////////////
// DISPOSE
////////////////////////////////////////////////////////////////////////////
public function dispose():void
{
developButton.removeEventListener(MouseEvent.CLICK, handleDevelopButtonClicked);
manageButton.removeEventListener(MouseEvent.CLICK, handleManageButtonClicked);
}
}
}

Stopping a function to run more than once in a period of time

I have this MouseEvent function that I have totally no idea why it fired twice. Is there a way I can disable the function in a period of time? I tried disabling the button, but seems like it directly called the function and does not trigger from the button.
Addition info:When I add in more object to the array, the function fired more time
The Class the handles the button
package classes
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import classes.playVideo;
import classes.playList;
import classes.viewType;
public class controlMenu extends MovieClip
{
private var playV:playVideo=new playVideo();
private var list:playList=new playList();
private var viewT:viewType = new viewType();
private static var con:controls = new controls();
private static var _buttonStatus:Boolean;
public function controlMenu()
{
}
//-------------------------------------------------------------
public function loadControlMenu():void
{
this.addEventListener(Event.ADDED_TO_STAGE,add2Stage);
}
private function add2Stage(e:Event):void
{
if (stage.numChildren == 1)
{
con.x=(stage.stageWidth-230)/2;
con.y=stage.stageHeight-(con.height+9);
addChild(con);
playButtonStatus();
con.soundBtn.addEventListener(MouseEvent.MOUSE_OVER, soundOver);
con.soundBtn.addEventListener(MouseEvent.MOUSE_OUT, soundOut);
con.soundBtn.addEventListener(MouseEvent.MOUSE_DOWN, soundDown);
stage.addEventListener(MouseEvent.MOUSE_UP, soundUp);
con.prev.addEventListener(MouseEvent.CLICK,prevClick);
con.next.addEventListener(MouseEvent.CLICK,nextClick);
}
}
private function playClick(e:MouseEvent):void
{
if (e.currentTarget.currentFrameLabel == "play" && playV.currentVideoStatus == "play")
{
e.currentTarget.gotoAndStop("pause");
playV.pauseStatus();
}
else if (e.currentTarget.currentFrameLabel=="pause" && playV.currentVideoStatus == "pause")
{
e.currentTarget.gotoAndStop("play");
playV.playStatus();
}
else if (e.currentTarget.currentFrameLabel == "play"&& playV.currentVideoStatus == "end")
{
playV.newVideo = "video/video" + list.currentIndex + ".flv";
}
}
private function playOver(e:MouseEvent):void
{
e.currentTarget.btn.gotoAndStop("over");
}
private function playOut(e:MouseEvent):void
{
e.currentTarget.btn.gotoAndStop("out");
}
//-------------------------------------------------------------
private function soundOver(e:MouseEvent):void
{
e.currentTarget.gotoAndStop("over");
}
private function soundOut(e:MouseEvent):void
{
if (e.buttonDown == false)
{
e.currentTarget.gotoAndStop("out");
}
}
private function soundDown(e:MouseEvent):void
{
var volumeBound:Rectangle = new Rectangle(-93,35,80,0);
e.currentTarget.startDrag(false, volumeBound);
stage.addEventListener(MouseEvent.MOUSE_MOVE,soundAdjust);
}
private function soundUp(e:MouseEvent):void
{
con.soundBtn.stopDrag();
con.soundBtn.gotoAndStop("out");
stage.removeEventListener(MouseEvent.MOUSE_MOVE,soundAdjust);
}
private function soundAdjust(e:MouseEvent):void
{
playV.adjustSound = ((con.soundBtn.x+93)*100)/80;
}
public function set adjustSoundBtnPos(a:Number):void
{
var newPos:Number = ((80*a)/100);
con.soundBtn.x = newPos - 93;
}
private function prevClick(e:MouseEvent):void
{
if (viewT.viewIn == "stream" && list.currentIndex > 1)
{
var goBack = list.currentIndex - 1;
list.currentIndex = goBack;
playV.newVideo = "video/video" + goBack + ".flv";
list.currentVideoLink = goBack;
}
}
private function nextClick(e:MouseEvent):void
{
if (viewT.viewIn == "stream" && list.currentIndex < list.vDataLength)
{
var goNext = list.currentIndex + 1;
list.currentIndex = goNext;
playV.newVideo = "video/video" + goNext + ".flv";
list.currentVideoLink = goNext;
}
}
//-------------------------------------------------------------
public function get currentStatus():String
{
return con.playBtn.currentFrameLabel;
}
public function resetPlayStatus():void
{
con.playBtn.gotoAndStop("play");
}
//-------------------------------------------------------------
public function set buttonStatus(s:Boolean):void
{
_buttonStatus = s;
playButtonStatus();
}
public function playButtonStatus():void
{
if (_buttonStatus == true)
{
con.playBtn.buttonMode = true;
con.playBtn.addEventListener(MouseEvent.CLICK, playClick);
con.playBtn.addEventListener(MouseEvent.MOUSE_OVER, playOver);
con.playBtn.addEventListener(MouseEvent.MOUSE_OUT, playOut);
con.soundBtn.buttonMode = true;
con.soundBtn.mouseEnabled = true;
}
else
{
con.playBtn.buttonMode = false;
con.playBtn.removeEventListener(MouseEvent.CLICK, playClick);
con.playBtn.removeEventListener(MouseEvent.MOUSE_OVER, playOver);
con.playBtn.removeEventListener(MouseEvent.MOUSE_OUT, playOut);
con.soundBtn.buttonMode = false;
con.soundBtn.mouseEnabled = false;
}
}
}
}
The Class that cause the extra loop on mouseevent function
package classes
{
import flash.media.Video;
import flash.display.MovieClip;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.events.AsyncErrorEvent;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.utils.Timer;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.media.SoundTransform;
import flash.media.SoundMixer;
import flash.net.URLLoader;
import flash.net.URLRequest;
import classes.Playing;
import classes.progressBar;
import classes.controlMenu;
import classes.viewType;
import classes.downloadVideo;
import classes.playList;
import classes.playVideo;
public class playVideo extends MovieClip
{
private var Play:Playing = new Playing();
private var progressB:progressBar = new progressBar();
private var conM:controlMenu;
private var viewT:viewType=new viewType();
private var downloadV:downloadVideo;
private var list:playList;
private var vBox:MovieClip = new MovieClip();
private var nc:NetConnection;
private static var ns:NetStream;
private const buffer:Number = 2;
private static var videoURL:String;
private static var vid:Video = new Video();
private static var meta:Object = new Object();
private var durationSecs:Number;
private var durationMins:Number;
private var durSecsDisplay:String;
private var durMinsDisplay:String;
private static var videoDuration:String;
private static var t:Timer = new Timer(100);
private static var videoSound:SoundTransform = new SoundTransform();
private var arial:Arial = new Arial();
private static var durationTxt:TextField=new TextField();
private var durationTxtF:TextFormat=new TextFormat();
private var scrubForward:Boolean;
private static var currentStatus;
private static var nsArray:Array= new Array();
private var dummyArray:Array = new Array();
//--------------------------------------------------------------------------
private var videoLoader:URLLoader;
public function playVideo()
{
}
public function set newVideo(v:String):void
{
currentStatus = "play";
videoURL = v;
if (viewT.viewIn == "stream")
{
addVideo();
}
else if (viewT.viewIn=="download")
{
for (var i:uint=0; i<nsArray.length; i++)
{
if (nsArray[i] != null)
{
nsArray[i].close();
}
}
videoProperties();
soundF();
}
conM.resetPlayStatus();
}
public function videoFunction():void
{
vBox.graphics.beginFill(0x000000);
vBox.graphics.drawRect(0,36,668,410);
vBox.graphics.endFill();
addChild(vBox);
// Add the instance of vid to the stage
vid.width = vid.width * 2;
vid.height = vid.height * 1.5;
vid.x = vBox.width / 2 - vid.width / 2;
vid.y = vBox.height / 2 - vid.height / 2 + 36;
vBox.addChild(vid);
if (viewT.viewIn == "stream")
{
videoProperties();
}
soundF();
durationText();
}
public function videoProperties():void
{
nc=new NetConnection();
// Assign variable name for Net Connection
nc.connect(null);
// Assign Var for the NetStream Object using NetConnection
ns = new NetStream(nc);
// Add the buffer time to the video Net Stream
ns.bufferTime = buffer;
// Set client for Meta Data Function
ns.client = {};
ns.client.onMetaData = onMetaData;
// Attach netStream to our new Video Object
if (viewT.viewIn == "stream")
{
vid.attachNetStream(ns);
}
else if (viewT.viewIn == "download")
{
nsArray[list.currentIndex - 1] = ns;
dummyArray.push(ns);
vid.attachNetStream(ns);
}
addVideo();
}
private function addVideo():void
{
// Assign NetStream to start play automatically by default
if (viewT.viewIn == "stream" && videoURL == null)
{
videoURL = "video/video1.flv";
}
ns.play(videoURL);
conM= new controlMenu();
conM.buttonStatus = true;
progressB.progressBarStatus();
// Add Error listener and listeners for all of our buttons
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR,asyncErrorHandler);
currentStatus = "play";
t.addEventListener(TimerEvent.TIMER,onTick);
t.start();
}
private function asyncErrorHandler(event:AsyncErrorEvent):void
{
// Do whatever you want if an error arises
}
private function onMetaData(info:Object):void
{
meta = info;
/*for (meta in info)
{
trace(meta + ":" + info[meta]);
}*/
durationSecs = Math.floor(meta.duration);
durationMins = Math.floor(durationSecs / 60);
durationMins %= 60;
durationSecs %= 60;
if (durationMins < 10)
{
durMinsDisplay = "0" + durationMins;
}
else
{
durMinsDisplay = "" + durationMins;
}
if (durationSecs < 10)
{
durSecsDisplay = "0" + durationSecs;
}
else
{
durSecsDisplay = "" + durationSecs;
}
videoDuration = durMinsDisplay + ":" + durSecsDisplay;
Play.vDuration = videoDuration;
}
//--------------------------------------------------------------------------
public function prepareArray():void
{
list = new playList();
for (var i:uint=0; i<list.vDataLength; i++)
{
nsArray.push(null);
}
}
//--------------------------------------------------------------------------
private function onTick(event:TimerEvent):void
{
if (viewT.viewIn == "stream" || ns.bytesLoaded == ns.bytesTotal)
{
var nsSecs:Number = Math.floor(ns.time);
var nsMins:Number = Math.floor(nsSecs / 60);
nsMins %= 60;
nsSecs %= 60;
var nsSecsDisplay:String = "";
var nsMinsDisplay:String = "";
if (nsMins < 10)
{
nsMinsDisplay = "0" + nsMins;
}
else
{
nsMinsDisplay = "" + nsMins;
}
if (nsSecs < 10)
{
nsSecsDisplay = "0" + nsSecs;
}
else
{
nsSecsDisplay = "" + nsSecs;
}
durationTxt.text = nsMinsDisplay + ":" + nsSecsDisplay;
progressB.progressing = ns.time / meta.duration * 668;
}
else if (viewT.viewIn=="download" && ns.bytesLoaded!=ns.bytesTotal)
{
list.preloadFlv();
}
if (durationTxt.text == videoDuration)
{
currentStatus = "end";
t.stop();
t.removeEventListener(TimerEvent.TIMER,onTick);
ns.pause();
ns.seek(0);
}
}
//--------------------------------------------------------------------------
private function soundF():void
{
var soundAmount:Number = 7;
if (viewT.viewIn == "stream")
{
ns.soundTransform = videoSound;
videoSound.volume = soundAmount / 10;
conM.adjustSoundBtnPos = soundAmount * 10;
}
else if (viewT.viewIn=="download")
{
if (dummyArray.length == 1 && ns != null)
{
ns.soundTransform = videoSound;
videoSound.volume = soundAmount / 10;
conM.adjustSoundBtnPos = soundAmount * 10;
}
else if (dummyArray.length> 1 && ns!=null)
{
ns.soundTransform = videoSound;
}
}
}
public function set adjustSound(s:Number):void
{
videoSound.volume = s / 100;
ns.soundTransform = videoSound;
}
//--------------------------------------------------------------------------
private function durationText():void
{
durationTxtF = new TextFormat();
durationTxtF.size = 12;
durationTxtF.leftMargin = 5;
durationTxtF.font = arial.fontName;
durationTxt.defaultTextFormat = durationTxtF;
durationTxt.selectable = false;
durationTxt.textColor = 0x999999;
durationTxt.width = 50;
durationTxt.height = 22;
durationTxt.x = 476;
durationTxt.y = 477;
durationTxt.text = "00:00";
addChild(durationTxt);
}
//--------------------------------------------------------------------------
public function get Duration():String
{
return videoDuration;
}
public function playStatus():void
{
conM=new controlMenu();
if (conM.currentStatus == "play")
{
ns.resume();
updateProgress();
}
if (currentStatus == "pause")
{
currentStatus = "play";
t.start();
}
}
public function pauseStatus():void
{
ns.pause();
t.stop();
trace("pause");
if (currentStatus == "play")
{
currentStatus = "pause";
}
}
public function get currentVideoStatus():String
{
return currentStatus;
}
public function restartVideo():void
{
ns.resume();
}
//--------------------------------------------------------------------------
public function updateProgress():void
{
ns.seek((progressB.currentProgress / 668) *meta.duration);
}
public function get nsBytesTotal():Number
{
return ns.bytesTotal;
}
public function get nsBytesLoaded():Number
{
return ns.bytesLoaded;
}
public function get getVideoURL():String
{
return videoURL;
}
}
}
I strongly, strongly recommend against doing some sort of flag or timer hack to get around an unexplained behavior - that leads to code bloat and down the line it'll cause you more problems in the long run.
It's much, much, much better to understand why it's calling your function twice. Invest the time in figuring that out (do you have listeners set on multiple display objects? Is this some sort of bubbling issue? Could it be your mouse? Try a clean flash project with just a handler and see if that calls twice, etc), and not only will your code be better and faster but you'll also learn a lot in the process.
You could make a variable so it only runs once. Something like...
var runOnce:Boolean = false;
button.addEventListener(MouseEvent.CLICK, testEvent);
function testEvent(e:Event):void{
if(runOnce == false){
//do stuff here
runOnce = true;
}
It's a bit lazy, but you get the idea.