Remove Children Of a Different Class As3 - actionscript-3

I have added many objects to the stage (in the Achievements.as class) to create an achievements board. I want to remove all of the children from the main.as class when someone presses a back button is there a way of doing this. Also, is there a way of creating a custom textField class where each textField.selectable = false without having to assign it to each one individually.
public static var texts:Vector.<TextField> = new Vector.<TextField>();
public static var titleTxt:Vector.<TextField> = new Vector.<TextField>();
public static var descripTxt:Vector.<TextField> = new Vector.<TextField>();
public static var rewardTxt:Vector.<TextField> = new Vector.<TextField>();
public static var achCoins:Vector.<MovieClip> = new Vector.<MovieClip>();
for (var j:int = 0; j < 30; j++)
{
achCoins[j].x = 240;
achCoins[j].y = 45 + j * 70;
addChild(achCoins[j]);
descripTxt[j].x = 0;
descripTxt[j].y = 30 + 70 * j;
//descripTxt[j].antiAliasType = AntiAliasType.ADVANCED;
descripTxt[j].defaultTextFormat = tf2;
descripTxt[j].text = descriptext[j];
descripTxt[j].embedFonts = true;
addChild(descripTxt[j]);
titleTxt[j].x = 0;
titleTxt[j].y = j * 70;
//titleTxt[j].antiAliasType = AntiAliasType.ADVANCED;
titleTxt[j].defaultTextFormat = tf3;
titleTxt[j].text = titletext[j];
titleTxt[j].embedFonts = true;
addChild(titleTxt[j]);
rewardTxt[j].x = 200;
rewardTxt[j].y = 30 + j * 70;
rewardTxt[j].text = reward[j].toString();
rewardTxt[j].setTextFormat(tf1);
rewardTxt[j].embedFonts = true;
rewardTxt[j].textColor = 0x000000;
addChild(rewardTxt[j]);
texts[j].text = Main.achievement[j] + "/" + totnum[j];
texts[j].setTextFormat(tf1);
texts[j].x = 200;
texts[j].y = j * 70;
texts[j].embedFonts = true;
addChild(texts[j]);
}
I then remove the children using this code
for (var k:int = 0; k < 30; k++)
{
removeChild(achievementback.descripTxt[k]);
removeChild(achievementback.titleTxt[k]);
removeChild(achievementback.rewardTxt[k]);
removeChild(achievementback.texts[k]);
}
I get the error
1119: Access of possibly undefined property descripTxt through a
reference with static type Achievements.
for (var i:int = 0; i < 30; i++)
{
texts.push(new TextField());
titleTxt.push(new TextField());
rewardTxt.push(new TextField());
descripTxt.push(new TextField());
achCoins.push(new coinSmall());
{
In Achievements.as Class
public function RemoveTextboxes(){
for (var k:int = 0; k < 30; k++)
{
removeChild(descripTxt[k]);
removeChild(titleTxt[k]);
removeChild(rewardTxt[k]);
removeChild(texts[k]);
}
}
In Main.as Class
achievementback.RemoveTextBoxes()
Here is my whole achievements class
package
{
import flash.display.MovieClip;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.display.Shape;
import flash.display.Graphics;
import flash.text.AntiAliasType;
public class Achievements extends MovieClip
{
public var backRect:Shape = new Shape();
public var coinsmall:MovieClip = new coinSmall();
public var titleText:MyTextField = new MyTextField();
public var descripText:MyTextField = new MyTextField();
public var reward_txt:MyTextField = new MyTextField();
public static var texts:Vector.<TextField> = new Vector.<TextField>();
public static var titleTxt:Vector.<TextField> = new Vector.<TextField>();
public static var descripTxt:Vector.<TextField> = new Vector.<TextField>();
public static var rewardTxt:Vector.<TextField> = new Vector.<TextField>();
public static var achCoins:Vector.<MovieClip> = new Vector.<MovieClip>();
public var tf1:TextFormat = new TextFormat();
public var tf2:TextFormat = new TextFormat();
public var tf3:TextFormat = new TextFormat();
//Achievement Variables
public var descriptext:Array = new Array();
public static var acharr:Array = new Array();
public var titletext:Array = new Array();
public var reward:Array = new Array(25,50,250,500,200,2000,10,100,500,10,25,50,10,25,100,25,25,50,50,100,500,500,5,5,5,50,10,50,100,250);
public function Achievements()
{
//Defining Objects
//Set Up Text Formats
//Text Format 1
tf1.font = "Myriad pro";
tf1.size = 20;
tf1.color = 0x660000;
tf1.align = "right";
//Text Format 2
tf2.size = 16;
tf2.color = 0xB8461D;
tf2.font = "Myriad Pro";
tf2.align = "center";
//Text Format 3
tf3.size = 23;
tf3.color = 0x660000;
tf3.font = "Myriad Pro";
tf3.align = "center";
//Text Box: Fraction Completed
//Text Box: Reward Amount For Each Achievement
//Text Box: Description of Achievement
for (var i:int = 0; i < 30; i++)
{
texts.push(new TextField());
titleTxt.push(new TextField());
rewardTxt.push(new TextField());
descripTxt.push(new TextField());
achCoins.push(new coinSmall());
backRect.graphics.beginFill(0x86B46D, 0.7);
backRect.graphics.drawRoundRect(0, i*70, 300, 60, 10, 10);
backRect.graphics.endFill();
addChild(backRect);
}
//change the text in a loop;
var acharr:Array = new Array();
var totnum:Array = new Array(50,100,500,1000,5,10,10,100,500,25,50,100,1,1,3,1,50,100,50,100,2,5,5,5,5,20,10,50,100,250);
for (var j:int = 0; j < 30; j++)
{
achCoins[j].x = 240;
achCoins[j].y = 45 + j * 70;
addChild(achCoins[j]);
descripTxt[j].width = 225;
descripTxt[j].height = 30;
descripTxt[j].x = 0;
descripTxt[j].y = 30 + 70 * j;
//descripTxt[j].antiAliasType = AntiAliasType.ADVANCED;
descripTxt[j].defaultTextFormat = tf2;
descripTxt[j].text = descriptext[j];
descripTxt[j].embedFonts = true;
addChild(descripTxt[j]);
titleTxt[j].width = 225;
titleTxt[j].height = 30;
titleTxt[j].x = 0;
titleTxt[j].y = j * 70;
//titleTxt[j].antiAliasType = AntiAliasType.ADVANCED;
titleTxt[j].defaultTextFormat = tf3;
titleTxt[j].text = titletext[j];
titleTxt[j].embedFonts = true;
addChild(titleTxt[j]);
rewardTxt[j].width = 100;
rewardTxt[j].height = 30;
rewardTxt[j].selectable = false;
rewardTxt[j].x = 200;
rewardTxt[j].y = 30 + j * 70;
rewardTxt[j].text = reward[j].toString();
rewardTxt[j].setTextFormat(tf1);
rewardTxt[j].embedFonts = true;
rewardTxt[j].textColor = 0x000000;
addChild(rewardTxt[j]);
texts[j].text = acharr[j] + "/" + totnum[j];
texts[j].setTextFormat(tf1);
texts[j].width = 100;
texts[j].height = 30;
texts[j].selectable = false;
texts[j].x = 200;
texts[j].y = j * 70;
texts[j].embedFonts = true;
addChild(texts[j]);
}
}
public function RemoveTextboxes(){
for (var k:int = 0; k < 30; k++)
{
removeChild(descripTxt[k]);
removeChild(titleTxt[k]);
removeChild(rewardTxt[k]);
removeChild(texts[k]);
}
}}
}
The arrays descriptext:Array acharr:Array titletext:Array All have the correct content in them but it is a lot of text so I took it out to post this
Here is the code I am using to remove the children from Main.as
function achievementExit():void
{
removeChild(back1);
removeChild(coin_sm);
removeChild(coinAmt);
removeChild(completed);
removeChild(achTit);
removeChild(achback);
achievementback.RemoveTextBoxes()
removeChild(achievementback)
removeChild(scrollPane);
}

I had to slightly modify the code and comment out where you set the text in the boxes to get this to run (since I'm missing some code) But What seemed to be my issue is that the textboxes were getting removed but your green shape was staying on the stage. Added a vector to hold all those and added those to the remove function.
package {
import flash.display.MovieClip;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.display.Shape;
import flash.display.Graphics;
import flash.text.AntiAliasType;
public class Achievements extends MovieClip
{
public var coinsmall:MovieClip = new MovieClip();
public var titleText:TextField = new TextField();
public var descripText:TextField = new TextField();
public var reward_txt:TextField = new TextField();
public static var texts:Vector.<TextField> = new Vector.<TextField>();
public static var titleTxt:Vector.<TextField> = new Vector.<TextField>();
public static var descripTxt:Vector.<TextField> = new Vector.<TextField>();
public static var rewardTxt:Vector.<TextField> = new Vector.<TextField>();
public static var achCoins:Vector.<MovieClip> = new Vector.<MovieClip>();
public static var graphix:Vector.<Shape> = new Vector.<Shape>();
public var tf1:TextFormat = new TextFormat();
public var tf2:TextFormat = new TextFormat();
public var tf3:TextFormat = new TextFormat();
//Achievement Variables
public var descriptext:Array = new Array();
public static var acharr:Array = new Array();
public var titletext:Array = new Array();
public var reward:Array = new Array(25,50,250,500,200,2000,10,100,500,10,25,50,10,25,100,25,25,50,50,100,500,500,5,5,5,50,10,50,100,250);
public function Achievements()
{
//Defining Objects
//Set Up Text Formats
//Text Format 1
tf1.font = "Myriad pro";
tf1.size = 20;
tf1.color = 0x660000;
tf1.align = "right";
//Text Format 2
tf2.size = 16;
tf2.color = 0xB8461D;
tf2.font = "Myriad Pro";
tf2.align = "center";
//Text Format 3
tf3.size = 23;
tf3.color = 0x660000;
tf3.font = "Myriad Pro";
tf3.align = "center";
for (var i:int = 0; i < 30; i++)
{
descriptext.push("THIS IS " + i);
texts.push(new TextField());
titleTxt.push(new TextField());
rewardTxt.push(new TextField());
descripTxt.push(new TextField());
achCoins.push(new MovieClip());
var backRect:Shape = new Shape();
backRect.graphics.beginFill(0x86B46D, 0.7);
backRect.graphics.drawRoundRect(0, i*70, 300, 60, 10, 10);
backRect.graphics.endFill();
graphix.push(backRect);
addChild(backRect);
}
//change the text in a loop;
var acharr:Array = new Array();
var totnum:Array = new Array(50,100,500,1000,5,10,10,100,500,25,50,100,1,1,3,1,50,100,50,100,2,5,5,5,5,20,10,50,100,250);
for (var j:int = 0; j < 30; j++)
{
achCoins[j].x = 240;
achCoins[j].y = 45 + j * 70;
addChild(achCoins[j]);
descripTxt[j].width = 225;
descripTxt[j].height = 30;
descripTxt[j].x = 0;
descripTxt[j].y = 30 + 70 * j;
//descripTxt[j].antiAliasType = AntiAliasType.ADVANCED;
descripTxt[j].defaultTextFormat = tf2;
//descripTxt[j].text = descriptext[j];
descripTxt[j].embedFonts = true;
addChild(descripTxt[j]);
titleTxt[j].width = 225;
titleTxt[j].height = 30;
titleTxt[j].x = 0;
titleTxt[j].y = j * 70;
//titleTxt[j].antiAliasType = AntiAliasType.ADVANCED;
titleTxt[j].defaultTextFormat = tf3;
//titleTxt[j].text = titletext[j];
titleTxt[j].embedFonts = true;
addChild(titleTxt[j]);
rewardTxt[j].width = 100;
rewardTxt[j].height = 30;
rewardTxt[j].selectable = false;
rewardTxt[j].x = 200;
rewardTxt[j].y = 30 + j * 70;
//rewardTxt[j].text = reward[j].toString();
rewardTxt[j].setTextFormat(tf1);
rewardTxt[j].embedFonts = true;
rewardTxt[j].textColor = 0x000000;
addChild(rewardTxt[j]);
//texts[j].text = acharr[j] + "/" + totnum[j];
texts[j].setTextFormat(tf1);
texts[j].width = 100;
texts[j].height = 30;
texts[j].selectable = false;
texts[j].x = 200;
texts[j].y = j * 70;
texts[j].embedFonts = true;
addChild(texts[j]);
}
}
public function RemoveTextboxes(){
trace("removing")
for (var k:int = 0; k < 30; k++)
{
removeChild(descripTxt[k]);
removeChild(titleTxt[k]);
removeChild(rewardTxt[k]);
removeChild(texts[k]);
removeChild(graphix[k]);
}
}
}
}
I also had to change your custom classes back to MovieClip and TextBox since I didnt have source for those.

It should be:
for (var k:int = 0; k < 30; k++)
{
achievementback.removeChild(achievementback.descripTxt[k]);
achievementback.removeChild(achievementback.titleTxt[k]);
achievementback.removeChild(achievementback.rewardTxt[k]);
achievementback.removeChild(achievementback.texts[k]);
}
Update
Are you even adding those DisplayObjects to your vector arrays?

Related

How do I remove eventlisteners and objects from an array upon game completion?

I have written a drag and drop game and, for the most part, it works.
It runs and does what I need it to do.
However, I cannot figure out two things.
How to remove the toy objects from the screen and re-add them after game over.
How to remove the event listeners for dragging/collision action after game over has initiated.
At the moment, after score is displayed you can still drop items in the toybox and make the score rise even when game over has been displayed.
Does anyone have any idea what I am doing wrong?
I would love to figure this out but it is driving me crazy.
Any help would be great.
Here is my code ...
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.text.Font;
import flash.filters.GlowFilter;
public class MainGame extends MovieClip {
const BG_SPEED:int = 5;
const BG_MIN:int = -550;
const BG_MAX:int = 0;
const PBG_SPEED:int = 3;
var bg:BackGround = new BackGround;
var paraBg:ParaBg = new ParaBg;
var toybox:TargetBox = new TargetBox;
var toy:Toy = new Toy;
var tryAgain:TryAgain = new TryAgain;
var cheer:Cheer = new Cheer;
var eightBit:EightBit = new EightBit;
var countDown:Number = 30;
var myTimer:Timer = new Timer(1000, 30);
var myText:TextField = new TextField;
var myText2:TextField = new TextField;
var myTextFormat:TextFormat = new TextFormat;
var myTextFormat2:TextFormat = new TextFormat;
var font1:Font1 = new Font1;
var kids:Kids = new Kids;
var count:int = 0;
var finalScore:int = 0;
var score:Number = 0;
var toy1:Toy1 = new Toy1;
var toy2:Toy2 = new Toy2;
var toy3:Toy3 = new Toy3;
var toy4:Toy4 = new Toy4;
var toy5:Toy5 = new Toy5;
var toy6:Toy6 = new Toy6;
var toy7:Toy7 = new Toy7;
var toy8:Toy8 = new Toy8;
var toy9:Toy9 = new Toy9;
var toy10:Toy10 = new Toy10;
var toy11:Toy11 = new Toy11;
var toy12:Toy12 = new Toy12;
var toy13:Toy13 = new Toy13;
var toy14:Toy14 = new Toy14;
var toy15:Toy15 = new Toy15;
var toy16:Toy16 = new Toy16;
var toy17:Toy17 = new Toy17;
var toy18:Toy18 = new Toy18;
var toy19:Toy19 = new Toy19;
var toy20:Toy20 = new Toy20;
var toyArray:Array = new Array(toy1, toy2, toy3, toy4, toy5, toy6, toy7, toy8, toy9, toy10, toy11, toy12, toy13, toy14, toy15, toy16, toy17, toy18, toy19, toy20);
public function mainGame():void
{
trace("HI");
eightBit.play(0, 9999);
addChildAt(paraBg, 0);
addChildAt(bg, 1);
addChildAt(kids, 2);
kids.x = 310;
kids.y = 200;
addChild(toy);
toy.x = 306;
toy.y = 133;
addChild(toybox);
toybox.x = 295;
toybox.y = 90;
function addToys(xpos:int, ypos:int)
{
addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
for (var i:int = 0; i < toyArray.length; i++)
{
addToys(1140 * Math.random() + 20, 170 * Math.random() + 230);
}
}
public function bgScroll (e:Event)
{
stage.addEventListener(MouseEvent.MOUSE_UP, arrayDrop);
myTimer.addEventListener(TimerEvent.TIMER, countdown);
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerDone);
myTimer.start();
e.target.addEventListener(Event.ENTER_FRAME, collision);
if (stage.mouseX > 600 && bg.x > BG_MIN)
{
bg.x -= BG_SPEED;
paraBg.x -= PBG_SPEED;
for (var m:int=0; m< toyArray.length; m++)
{
(toyArray[m] as MovieClip).x -=BG_SPEED
}
}
else if (stage.mouseX < 50 && bg.x < BG_MAX)
{
bg.x += BG_SPEED;
paraBg.x += PBG_SPEED;
for (var j:int=0; j< toyArray.length; j++)
{
(toyArray[j] as MovieClip).x +=BG_SPEED
}
}
for (var k:int = 0; k < toyArray.length; k++)
{
toyArray[k].addEventListener(MouseEvent.MOUSE_DOWN, arrayGrab);
}
bg.addEventListener(Event.ENTER_FRAME, bgScroll);
} // End of BGScroll
public function collision (e:Event)
{
for (var l:int=0; l< toyArray.length; l++)
{
if (toyArray[l].hitTestObject(toy))
{
removeChild(toyArray[l]);
toyArray[l].x=100000;
toybox.gotoAndPlay(2);
cheer.play(1, 1);
score = score + 10;
trace(score);
}
if (score == 200)
{
timerDone();
myTimer.stop();
}
}
}
public function arrayGrab(e:MouseEvent)
{
e.target.startDrag();
}
public function arrayDrop(e:MouseEvent)
{
stopDrag();
}
public function resetGame(e:Event):void {
trace("CLICK");
countDown = 30;
myText.text = "0" + countDown.toString();
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerDone);
myTimer.reset();
removeChild(tryAgain);
myText2.visible = false;
score = 0;
}
public function countdown(e:TimerEvent):void
{
if (countDown > 0)
{
countDown--;
}
if (countDown < 10)
{
myText.text = "0" + countDown.toString();
myText.x = 270;
displayText();
}
else if (countDown < 20 && countDown > 9)
{
myText.text = countDown.toString();
myText.x = 280;
displayText();
}
else
{
myText.text = countDown.toString();
myText.x = 270;
displayText();
}
} // end of countdown function
public function displayText():void
{
myText.filters = [new GlowFilter(0x00FF00, 1.0, 5, 5, 4)];
addChild(myText);
myText.width = 500, myText.height = 50, myText.y = 10;
myTextFormat.size = 50, myTextFormat.font = font1.fontName;
myText.setTextFormat(myTextFormat);
}
public function displayText2():void
{ myText2.filters = [new GlowFilter(0xFF0000, 1.0, 5, 5, 4)];
addChild(myText2);
myText2.width = 500, myText2.height = 35, myText2.x = 204, myText2.y = 200;
myTextFormat2.size = 30, myTextFormat2.font = font1.fontName;
myText2.setTextFormat(myTextFormat2);
}
public function timerDone(e:TimerEvent=null):void
{
if (countDown == 0)
{
count = 0;
finalScore = score;
}
else
{
count = (30) - (myTimer.currentCount);
finalScore = (count * 10) + (score);
}
myText.text = "GAME OVER!";
myText.x = 195;
displayText();
myText2.text = "Your score = " + (finalScore);
displayText2();
addChild(tryAgain);
tryAgain.x = 300;
tryAgain.y = 300;
tryAgain.addEventListener(MouseEvent.CLICK, resetGame);
}
} // End of class
} //End of package
Nevermind ... solved it.
Easiest was was to change
function addToys(xpos:int, ypos:int)
{
addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
To
function addToys(xpos:int, ypos:int)
{
stage.addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
And then, in the timerDone function I added thisif statement ...
for (var m = 0; m < toyArray.length; m++) {
if (stage.contains(toyArray[m])) {
stage.removeChild(toyArray[m]);
}
Worked a treat!

How to get indexof a Bitmap image?

I am having a hard time to get an index of a bitmap image. I am not sure how should i suppose to do it.
What i am trying to do is:
1.)Loop a URLRequest and load bitmap pictures.
2.)Put them in individual _contentHolder
3.)Put everything in a viewport
4.)Check the index of the image when its clicked
Thanks for your time
Code
public var _contentHolder:Sprite = new Sprite;
public var _contentHolder1:Sprite;
public var loadedArray:Array = new Array;
public var blackBox:Sprite = new Sprite();
private var somedata:Array;
protected var Holder:Listing9 = new Listing9;
public var viewport:Viewport = new Viewport();
public var scroller:TouchScroller = new TouchScroller();
var my_url:Array = somedata;
function loadImage():void
{
somedata = SearchVectorTest.lists;
for (var i:int = 5; i < somedata.length; i++)
{
if (somedata[i])
{
var loader:Loader = new Loader();
loader.load(new URLRequest("http://www.rentaid.info/rent/" + somedata[i]));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoaded);
}
}
}
function onImageLoaded(e:Event):void
{
loadedArray.push(e.currentTarget.loader.content as Bitmap);
for (var i:int = 0; i < loadedArray.length; i++)
{
var currentY1:int = 200;
e.currentTarget.loader.content.height = 200;
e.currentTarget.loader.content.y += currentY1;
currentY1 += e.currentTarget.loader.content.height + 300;
_contentHolder.mouseChildren = false; // ignore children mouseEvents
_contentHolder.mouseEnabled = true; // enable mouse on the object - normally set to true by default
_contentHolder.useHandCursor = true; // add hand cursor on mouse over
_contentHolder.buttonMode = true;
_contentHolder.addChild(loadedArray[i]);
}
var viewport:Viewport = new Viewport();
viewport.y = 0;
viewport.addChild(_contentHolder);
var scroller:TouchScroller = new TouchScroller();
scroller.width = 300;
scroller.height = 265;
scroller.x = 10;
scroller.y = 100;
scroller.viewport = viewport;
addChild(scroller);
_contentHolder.addEventListener(MouseEvent.CLICK, gotoscene);
}
loadImage();
public function gotoscene(e:MouseEvent):void
{
BitmapArray.push(loadedArray);
var index:Number;
index = BitmapArray.indexOf(e.target);
trace(index);
trace(_contentHolder);
trace(_contentHolder.parent);
blackBox.graphics.beginFill(0x000000);
blackBox.graphics.drawRect(-1, -1, stage.width, stage.height);
blackBox.alpha = 0.7;
addChild(blackBox);
Holder.height = 300;
Holder.width = stage.width;
Holder.x = 0;
Holder.y = 100;
trace(blackBox);
trace(blackBox.parent);
addChild(Holder);
}
function gotoscene1(e:MouseEvent):void
{
removeChild(Holder);
removeChild(blackBox);
}

ActionScript 3.0 AddChild Function Not Working

I have tested out my code and the addchild won't work. No errors are outputted.
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.*;
import flash.events.*;
import flash.geom.Rectangle;
import flash.media.Sound;
import flash.text.*;
public class Game extends flash.display.MovieClip{
public static const STATE_INIT:int = 10;
public static const STATE_PLAY:int = 20;
public static const STATE_END_GAME:int = 30;
public var gameState:int = 0;
public var score:int = 0;
public var chances:int = 5;
public var bg:MovieClip;
public var enemies:Array;
public var player:MovieClip;
public var level:Number = 0;
public var scoreLabel:TextField = new TextField
public var levelLabel:TextField = new TextField
public var chancesLabel:TextField = new TextField
public var scoreText:TextField = new TextField
public var levelText:TextField = new TextField
public var chancesText:TextField = new TextField
public const SCOREBOARD_Y:Number = 380
public function Game(){
addEventListener(Event.ENTER_FRAME, gameLoop);
bg = new BackImage();
addChild(bg);
scoreLabel.text = "Score:";
levelLabel.text = "level:";
chancesLabel.text = "Misses:";
scoreText.text = "0";
levelText.text = "1";
chancesText.text = "5";
scoreLabel.y = SCOREBOARD_Y;
levelLabel.y = SCOREBOARD_Y;
chancesLabel.y = SCOREBOARD_Y;
scoreText.y = SCOREBOARD_Y;
levelText.y = SCOREBOARD_Y;
chancesText.y = SCOREBOARD_Y;
scoreLabel.x = 5;
scoreText.x = 50;
chancesLabel.x = 105;
chancesText.x = 155;
levelLabel.x = 205;
levelText.x = 260
addChild(scoreLabel);
addChild(levelLabel);
addChild(chancesLabel);
addChild(scoreText);
addChild(levelText);
addChild(chancesText);
gameState = STATE_INIT;
}
public function gameLoop(e:Event):void{
switch(gameState){
case STATE_INIT:
initGame();
break;
case STATE_PLAY:
playGame();
break;
case STATE_END_GAME:
endGame();
break;
}
}
public function initGame():void{
score = 0;
chances = 5;
player = new playerImage();
enemies = new Array();
level = 1;
levelText.text = level.toString();
addChild(player);
player.startDrag(true,new Rectangle(0,0,550,400))
gameState = STATE_PLAY
}
public function playGame():void{
player.rotation += 15;
makeEnemies();
moveEnemies();
testCollisions();
testForEnd();
}
public function makeEnemies():void{
var chance:Number = Math.floor(Math.random()*100);
var tempEnemy:MovieClip;
if (chance < 2 + level) {
tempEnemy = new EnemyImage()
tempEnemy.speed = 3 + level;
tempEnemy.gotoAndStop(Math.floor(Math.random()*5)+1);
tempEnemy.y = 435;
tempEnemy.x = Math.floor(Math.random()*515)
addChild(tempEnemy);
enemies.push(tempEnemy);
}
}
public function moveEnemies():void{
var tempEnemy:MovieClip;
for (var i:int = enemies.length -1;i >= 0;i--){
tempEnemy = enemies[i];
tempEnemy.y -= tempEnemy.speed;
if (tempEnemy.y < -35){
chances -= 1;
chancesText.text = chances.toString();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
public function testCollisions():void {
var sound:Sound = new Pop();
var tempEnemy:MovieClip;
for (var i:int = enemies.length -1;i >= 0;i--){
tempEnemy = enemies[i];
if(tempEnemy.hitTestObject(player)){
score++;
scoreText.text = score.toString();
sound.play();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
public function testForEnd():void{
if(chances == 5){
gameState = STATE_END_GAME;
}
else if(score > level*20) {
level++;
levelText.text = level.toString();
}
}
public function endGame():void{
for(var i:int = 0; i< enemies.length; i++) {
removeChild(enemies[i]);
}
enemies = [];
player.stopDrag()
}
}
}
I have already tried adding this. and stage. in front of addchild and it still doesn't work.
This inside a file called Game.as
When you create your Game instance you need to add it as a child to the stage:
// I would probably rename the variable to 'game'
// 1st character of a variable name is conventionally lower-case
// var game:Game = new Game();
var Script:Game = new Game();
this.addChild(Script);

Detect when the Shader is done mixing the audio

so this the code with it i am able to mix several tracks
with a Shader done in pixel bender.
the problem here i don't know when the mixing is finish or all the sound reache their end
to be able to save the bytearray into a file any Event or something like that
help plz ?
package
{
import flash.display.*;
import flash.media.*;
import flash.events.*;
import flash.net.*;
import flash.utils.*;
import fl.controls.Slider;
import org.bytearray.micrecorder.encoder.WaveEncoder;
[SWF(width='500', height='380', frameRate='24')]
public class AudioMixer extends Sprite{
[Embed(source = "sound2.mp3")] private var Track1:Class;
[Embed(source = "sound1.mp3")] private var Track2:Class;
[Embed(source = "mix.pbj",mimeType = "application/octet-stream")]
private var EmbedShader:Class;
private var shader:Shader = new Shader(new EmbedShader());
private var sound:Vector.<Sound> = new Vector.<Sound>();
private var bytes:Vector.<ByteArray> = new Vector.<ByteArray>();
private var sliders:Vector.<Slider> = new Vector.<Slider>();
private var graph:Vector.<Shape> = new Vector.<Shape>();
private var recBA:ByteArray = new ByteArray();
private var BUFFER_SIZE:int = 0x800;
public var playback:Sound = new Sound();
public var container:Sprite = new Sprite();
public var isEvent:Boolean = false;
public function AudioMixer():void{
container.y = stage.stageHeight * .5;
addChild(container);
sound.push(new Track1(), new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2(),new Track2());
for(var i:int = 0; i < sound.length; i++){
var slider:Slider = new Slider();
slider.maximum = 1;
slider.minimum = 0;
slider.snapInterval = 0.025;
slider.value = 0.8;
slider.rotation += -90;
slider.x = i * 40 + 25;
container.addChild(slider);
sliders.push(slider);
var line:Shape = new Shape();
line.graphics.lineStyle(1, 0x888888);
line.graphics.drawRect(i * 40 + 14, 0, 5, -80);
line.graphics.endFill();
container.addChild(line);
var shape:Shape = new Shape();
shape.graphics.beginFill(0x00cc00);
shape.graphics.drawRect(i * 40 + 15, 0, 3, -80);
shape.graphics.endFill();
container.addChild(shape);
graph.push(shape);
}
playback.addEventListener(SampleDataEvent.SAMPLE_DATA, onSoundData);
playback.play();
}
private function onSoundData(event:SampleDataEvent):void {
for(var i:int = 0; i < sound.length; i++){
bytes[i] = new ByteArray();
bytes[i].length = BUFFER_SIZE * 4 * 2;
sound[i].extract(bytes[i], BUFFER_SIZE);
var volume:Number = 0;
bytes[i].position = 0;
for(var j:int = 0; j < BUFFER_SIZE; j++){
volume += Math.abs(bytes[i].readFloat());
volume += Math.abs(bytes[i].readFloat());
}
volume = (volume / (BUFFER_SIZE * .5)) * sliders[i].value;
shader.data['track' + (i + 1)].width = BUFFER_SIZE / 1024;
shader.data['track' + (i + 1)].height = 512;
shader.data['track' + (i + 1)].input = bytes[i];
shader.data['vol' + (i + 1)].value = [sliders[i].value];
graph[i].scaleY = volume;
}
var shaderJob:ShaderJob = new ShaderJob(shader,event.data,BUFFER_SIZE / 1024,512);
shaderJob.start(true);
var shaderJob2:ShaderJob = new ShaderJob(shader,recBA,BUFFER_SIZE / 1024,512);
shaderJob2.start(true);
}
}
}
You can tell when a shader has completed it's job using the ShaderEvent.COMPLETE listener. Like so:
shaderJob.addEventListener(ShaderEvent.COMPLETE, onShaderComplete);
private function onShaderComplete(e:Event):void
{
//Do Something here
}
See this link for more details.
One thing about your code though. You're doing this shader job inside of a sampleDataEvent and I can see this being problematic (possibly) in the sense that your mixing may be out of sync with your playback (that is, if you plan on mixing live and writing the mixed data back into the sound stream). Anyway that's perhaps an issue for a new question. This should solve your problem with needing to know when the mixing is complete.
Note you also need to add "false" to the shaderJob.start(false) function. From the documentation about the ShaderEvent.COMPLETE:
"Dispatched when a ShaderJob that executes asynchronously finishes processing the data using the shader. A ShaderJob instance executes asynchronously when the start() method is called with a false value for the waitForCompletion parameter."
Update
In response to your inquiry about how to only process inside the sampleDataEvent if the sound isnt being processed:
private var isProcessing:Boolean = false;
private function onSoundData(event:SampleDataEvent):void {
if(isProcessing != true){
for(var i:int = 0; i < sound.length; i++){
bytes[i] = new ByteArray();
bytes[i].length = BUFFER_SIZE * 4 * 2;
sound[i].extract(bytes[i], BUFFER_SIZE);
var volume:Number = 0;
bytes[i].position = 0;
for(var j:int = 0; j < BUFFER_SIZE; j++){
volume += Math.abs(bytes[i].readFloat());
volume += Math.abs(bytes[i].readFloat());
}
volume = (volume / (BUFFER_SIZE * .5)) * sliders[i].value;
shader.data['track' + (i + 1)].width = BUFFER_SIZE / 1024;
shader.data['track' + (i + 1)].height = 512;
shader.data['track' + (i + 1)].input = bytes[i];
shader.data['vol' + (i + 1)].value = [sliders[i].value];
graph[i].scaleY = volume;
}
var shaderJob:ShaderJob = new ShaderJob(shader,event.data,BUFFER_SIZE / 1024,512);
shaderJob.start(false);
shaderJob.addEventListener(ShaderEvent.COMPLETE, onShaderComplete);
var shaderJob2:ShaderJob = new ShaderJob(shader,recBA,BUFFER_SIZE / 1024,512);
shaderJob2.start(false);
}
}
private function onShaderComplete(e:ShaderEvent):void
{
//Do something here
isProcessing = false;
}

doubt regarding carrying data in custom events using actionscript

I am working on actionscript to generate a SWF dynamically using JSON data coming from an HTTP request. I receive the data on creationComplete and try to generate a tree like structure. I don’t create the whole tree at the same time. I create 2 levels, level 1 and level 2. My goal is to attach custom events on the panels which represent tree nodes. When users click the panels, it dispatches custom events and try to generate the next level. So, it goes like this :
On creation complete -> get JSON-> create top tow levels -> click on level 2-> create the level 2 and level 3 -> click on level 3-> create level 3 and 4. …and so on and so on. I am attaching my code with this email. Please take a look at it and if you have any hints on how you would do this if you need to paint a tree having total level number = “n” where n = 0 to 100
Should I carry the data around in CustomPageClickEvent class.
[code]
import com.iwobanas.effects.*;
import flash.events.MouseEvent;
import flash.filters.BitmapFilterQuality;
import flash.filters.BitmapFilterType;
import flash.filters.GradientGlowFilter;
import mx.controls.Alert;
private var roundedMask:Sprite;
private var panel:NewPanel;
public var oldPanelIds:Array = new Array();
public var pages:Array = new Array();
public var delPages:Array = new Array();
public function DrawPlaybook(pos:Number,title:String,chld:Object):void {
panel = new NewPanel(chld);
panel.title = title;
panel.name=title;
panel.width = 100;
panel.height = 80;
panel.x=pos+5;
panel.y=40;
var gradientGlow:GradientGlowFilter = new GradientGlowFilter();
gradientGlow.distance = 0;
gradientGlow.angle = 45;
gradientGlow.colors = [0xFFFFF0, 0xFFFFFF];
gradientGlow.alphas = [0, 1];
gradientGlow.ratios = [0, 255];
gradientGlow.blurX = 10;
gradientGlow.blurY = 10;
gradientGlow.strength = 2;
gradientGlow.quality = BitmapFilterQuality.HIGH;
gradientGlow.type = BitmapFilterType.OUTER;
panel.filters =[gradientGlow];
this.rawChildren.addChild(panel);
pages.push(panel);
panel.addEventListener(MouseEvent.CLICK,
function(e:MouseEvent){onClickHandler(e,title,chld)});
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED,
function(e:CustomPageClickEvent){onCustomPanelClicked(e,title)});
}
public function onClickHandler(e:MouseEvent,title:String,chld:Object):void {
for each(var stp1:NewPanel in pages){
if(stp1.title==title){
var eventObj:CustomPageClickEvent = new CustomPageClickEvent("panelClicked");
eventObj.panelClicked = stp1;
dispatchEvent(eventObj);
}
}
}
private function onCustomPanelClicked(e:CustomPageClickEvent,title:String):void {
Alert.show("onCustomPanelClicked" + title);
var panel:NewPanel;
for each(var stp:NewPanel in pages){
startAnimation(e,stp);
}
if(title == e.panelClicked.title){
panel = new NewPanel(null);
panel.title = title;
panel.name=title;
panel.width = 150;
panel.height = 80;
panel.x=100;
panel.y=40;
this.rawChildren.addChild(panel);
var slideRight:SlideRight = new SlideRight();
slideRight.target=panel;
slideRight.duration=750;
slideRight.showTarget=true;
slideRight.play();
var jsonData = this.map.getValue(title);
var posX:Number = 50;
var posY:Number = 175;
for each ( var pnl:NewPanel in pages){
pages.pop();
}
for each ( var stp1:Object in jsonData.children){
panel = new NewPanel(null);
panel.title = stp1.text;
panel.name=stp1.id;
panel.width = 100;
panel.id=stp1.id;
panel.height = 80;
panel.x = posX;
panel.y=posY;
posX+=150;
var s:String="hi" + stp1.text;
panel.addEventListener(MouseEvent.CLICK,
function(e:MouseEvent){onChildClick(e,s);});
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED,
function(e:CustomPageClickEvent){onCustomPnlClicked(e)});
this.rawChildren.addChild(panel);
pages.push(panel);
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED,
function(e:CustomPageClickEvent){onCustomPanelClicked(e,title)});
var slide:SlideUp = new SlideUp();
slide.target=panel;
slide.duration=1500;
slide.showTarget=false;
slide.play();
}
}
}
public function onChildClick(e:MouseEvent,s:String):void {
for each(var stp1:NewPanel in pages){
if(stp1.title==e.currentTarget.title){
var eventObj:CustomPageClickEvent = new CustomPageClickEvent("panelClicked");
eventObj.panelClicked = stp1;
dispatchEvent(eventObj);
}
}
}
private function onCustomPnlClicked(e:CustomPageClickEvent):void {
for each ( var pnl:NewPanel in pages){
pages.pop();
}
}
private function fadePanel(event:Event,panel:NewPanel):void{
panel.alpha -= .005;
if (panel.alpha <= 0){
panel.removeEventListener(Event.ENTER_FRAME,
function(e:Event){fadePanel(e,panel);});
};
panel.title="";
}
private function startAnimation(event:CustomPageClickEvent,panel:NewPanel):void{
panel.addEventListener(Event.ENTER_FRAME,
function(e:Event){fadePanel(e,panel)});
}
[/code]
Thanks in advance.
Palash
completely forgot i don't have enough rep to edit...
import com.iwobanas.effects.*;
import flash.events.MouseEvent;
import flash.filters.BitmapFilterQuality;
import flash.filters.BitmapFilterType;
import flash.filters.GradientGlowFilter;
import mx.controls.Alert;
private var roundedMask:Sprite;
private var panel:NewPanel;
public var oldPanelIds:Array = new Array();
public var pages:Array = new Array();
public var delPages:Array = new Array();
public function DrawPlaybook(pos:Number,title:String,chld:Object):void {
panel = new NewPanel(chld);
panel.title = title;
panel.name=title;
panel.width = 100;
panel.height = 80;
panel.x=pos+5;
panel.y=40;
var gradientGlow:GradientGlowFilter = new GradientGlowFilter();
gradientGlow.distance = 0;
gradientGlow.angle = 45;
gradientGlow.colors = [0xFFFFF0, 0xFFFFFF];
gradientGlow.alphas = [0, 1];
gradientGlow.ratios = [0, 255];
gradientGlow.blurX = 10;
gradientGlow.blurY = 10;
gradientGlow.strength = 2;
gradientGlow.quality = BitmapFilterQuality.HIGH;
gradientGlow.type = BitmapFilterType.OUTER;
panel.filters = [gradientGlow];
this.rawChildren.addChild(panel);
pages.push(panel);
panel.addEventListener(MouseEvent.CLICK, function(e:MouseEvent){onClickHandler(e,title,chld)});
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED, function(e:CustomPageClickEvent){onCustomPanelClicked(e,title)});
}
public function onClickHandler(e:MouseEvent,title:String,chld:Object):void {
for each(var stp1:NewPanel in pages){
if(stp1.title==title){
var eventObj:CustomPageClickEvent = new CustomPageClickEvent("panelClicked");
eventObj.panelClicked = stp1;
dispatchEvent(eventObj);
}
}
}
private function onCustomPanelClicked(e:CustomPageClickEvent,title:String):void {
Alert.show("onCustomPanelClicked" + title);
var panel:NewPanel;
for each(var stp:NewPanel in pages){
startAnimation(e,stp);
}
if(title == e.panelClicked.title){
panel = new NewPanel(null);
panel.title = title;
panel.name=title;
panel.width = 150;
panel.height = 80;
panel.x=100;
panel.y=40;
this.rawChildren.addChild(panel);
var slideRight:SlideRight = new SlideRight();
slideRight.target=panel;
slideRight.duration=750;
slideRight.showTarget=true;
slideRight.play();
var jsonData = this.map.getValue(title);
var posX:Number = 50;
var posY:Number = 175;
for each ( var pnl:NewPanel in pages){
pages.pop();
}
for each ( var stp1:Object in jsonData.children){
panel = new NewPanel(null);
panel.title = stp1.text;
panel.name=stp1.id;
panel.width = 100;
panel.id=stp1.id;
panel.height = 80;
panel.x = posX;
panel.y=posY;
posX += 150;
var s:String="hi" + stp1.text;
panel.addEventListener(MouseEvent.CLICK, function(e:MouseEvent){onChildClick(e,s);});
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED, function(e:CustomPageClickEvent){onCustomPnlClicked(e)});
this.rawChildren.addChild(panel);
pages.push(panel);
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED, function(e:CustomPageClickEvent){onCustomPanelClicked(e,title)});
var slide:SlideUp = new SlideUp();
slide.target=panel;
slide.duration=1500;
slide.showTarget=false;
slide.play();
}
}
}
public function onChildClick(e:MouseEvent,s:String):void {
for each(var stp1:NewPanel in pages){
if(stp1.title==e.currentTarget.title){
var eventObj:CustomPageClickEvent = new CustomPageClickEvent("panelClicked");
eventObj.panelClicked = stp1;
dispatchEvent(eventObj);
}
}
}
private function onCustomPnlClicked(e:CustomPageClickEvent):void {
for each ( var pnl:NewPanel in pages){
pages.pop();
}
}
private function fadePanel(event:Event,panel:NewPanel):void{
panel.alpha -= .005;
if (panel.alpha <= 0){
panel.removeEventListener(Event.ENTER_FRAME,
function(e:Event){fadePanel(e,panel);});
};
panel.title="";
}
private function startAnimation(event:CustomPageClickEvent,panel:NewPanel):void{
panel.addEventListener(Event.ENTER_FRAME,
function(e:Event){fadePanel(e,panel)});
}