Simplifying function on ActionScript 3.0 - actionscript-3

Heloo, I'd like to make an animation in my program. I've tried a function and its worked. But, this function is gonna be very very long if I continue. Here is my function.
if(jalan)
{
dt1 += t;
s1 = -A*Math.sin(w*dt1);
P1.y = s01 + s1;
var delay1:Timer = new Timer(1000,1);
delay1.addEventListener(TimerEvent.TIMER,f_delay1);
delay1.start();
function f_delay1(event:TimerEvent)
{
dt2 += t;
s2 = -A*Math.sin(w*dt2);
P2.y = s02 + s2;
var delay2:Timer = new Timer(1000,1);
delay2.addEventListener(TimerEvent.TIMER,f_delay2);
delay2.start();
function f_delay2(event:TimerEvent)
{
dt3 += t;
s3 = -A*Math.sin(w*dt3);
P3.y = s03 + s3;
var delay3:Timer = new Timer(1000,1);
delay3.addEventListener(TimerEvent.TIMER,f_delay3);
delay3.start();
function f_delay3(event:TimerEvent)
{
dt4 += t;
s4 = -A*Math.sin(w*dt4);
P4.y = s04 + s4;
var delay4:Timer = new Timer(1000,1);
delay4.addEventListener(TimerEvent.TIMER,f_delay4);
delay4.start();
function f_delay4(event:TimerEvent)
{
dt5 += t;
s5 = -A*Math.sin(w*dt5);
P5.y = s05 + s5;
var delay5:Timer = new Timer(1000,1);
delay5.addEventListener(TimerEvent.TIMER,f_delay5);
delay5.start();
function f_delay5(event:TimerEvent)
{
dt6 += t;
s6 = -A*Math.sin(w*dt6);
P6.y = s06 + s6;
var delay6:Timer = new Timer(1000,1);
delay6.addEventListener(TimerEvent.TIMER,f_delay6);
delay6.start();
function f_delay6(event:TimerEvent)
{
dt7 += t;
s7 = -A*Math.sin(w*dt7);
P7.y = s07 + s7;
var delay7:Timer = new Timer(1000,1);
delay7.addEventListener(TimerEvent.TIMER,f_delay7);
delay7.start();
function f_delay7(event:TimerEvent)
{
dt8 += t;
s8 = -A*Math.sin(w*dt8);
P8.y = s08 + s8;
var delay8:Timer = new Timer(1000,1);
delay8.addEventListener(TimerEvent.TIMER,f_delay8);
delay8.start();
function f_delay8(event:TimerEvent)
{
dt9 += t;
s9 = -A*Math.sin(w*dt9);
P9.y = s09 + s9;
var delay9:Timer = new Timer(1000,1);
delay9.addEventListener(TimerEvent.TIMER,f_delay9);
delay9.start();
function f_delay9(event:TimerEvent)
{
dt10 += t;
s10 = -A*Math.sin(w*dt10);
P10.y = s010 + s10;
var delay10:Timer = new Timer(1000,1);
delay10.addEventListener(TimerEvent.TIMER,f_delay10);
delay10.start();
function f_delay10(event:TimerEvent)
{
dt11 += t;
s11 = -A*Math.sin(w*dt11);
P11.y = s011 + s11;
var delay11:Timer = new Timer(1000,1);
delay11.addEventListener(TimerEvent.TIMER,f_delay11);
delay11.start();
function f_delay11(event:TimerEvent)
{
dt12 += t;
s12 = -A*Math.sin(w*dt12);
P12.y = s012 + s12;
}
}
}
}
}
}
}
}
}
}
}
}
Is there another function that can simplify this function?
Thanks
Making some wave animation by vibrating some particles in a pattern with delay in each particle

When processing data in a similar manner, it is always about Arrays and loops, even if there is a need for delay between loop iterations.
Something like that, I guess. Not tested, but the idea should be clear.
import flash.utils.setTimeout;
// Array of Arrays
var Sequence:Array =
[
{dt:dt1, P:P1, s0:s01},
{dt:dt2, P:P2, s0:s02},
{dt:dt3, P:P3, s0:s03},
{dt:dt4, P:P4, s0:s04},
{dt:dt5, P:P5, s0:s05},
{dt:dt6, P:P6, s0:s06},
{dt:dt7, P:P7, s0:s07},
{dt:dt8, P:P8, s0:s08},
{dt:dt9, P:P9, s0:s09},
{dt:dt10, P:P10, s0:s010},
{dt:dt11, P:P11, s0:s011},
];
function onNext(index:int = 0):void
{
// Checking, if there anything left on the Sequence to do.
if (index >= Sequence.length)
{
return;
}
// Extract the first tuple of data.
var aData:Object = Sequence[index];
// Your initial logic here.
aData.dt += t;
aData.P.y = aData.s0 - A * Math.sin(w * aData.dt);
// Wait before addressing the next particle.
setTimeout(onNext, 1000, index + 1);
}
if (jalan)
{
// The initial call.
onNext();
}

Related

Timer related error in flash, TypeError #1009

I used a timer in my flash application, and I have this particular error below:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at FlashGame_fla::MainTimeline/toTimeCode()
at FlashGame_fla::MainTimeline/timerTickHandler()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
Below is my code for this particular flash game application. It's a game where the player collects as many items as possible within a specific time:
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.geom.Rectangle;
menuButton.addEventListener(MouseEvent.CLICK, evilToMenu);
rulesButton.addEventListener(MouseEvent.CLICK, toggleRule);
gameRules.addEventListener(MouseEvent.CLICK, toggleRule);
gameRules.visible = false;
gameRules.buttonMode = true;
evilGameOverMC.visible = false;
evilWinLose.visible = false;
playAgainBtn.visible = false;
toMenuBtn.visible = false;
var pLives:int = 3;
var pEvilScore:int = 0;
var pItems:int = 10;
var daveMC:MovieClip;
var cGameObjs:Array = new Array();
var timer:Timer = new Timer(100, 300);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 15000;
//var cPlayerData:Object;
//var cSavedGameData:SharedObject;
addCharacter();
addBots();
addItems();
scoreDisplay.text = "" + pEvilScore;
livesDisplay.text = pLives + " lives";
function evilToMenu(Event:MouseEvent):void
{
removeLeftovers();
removeChild(daveMC);
timer.stop();
gotoAndStop("menu");
}
function timerTickHandler(Event:TimerEvent):void
{
timerCount -= 100;
toTimeCode(timerCount);
if (timerCount <= 0)
{
gameOver(false);
}
}
function toTimeCode(milliseconds:int): void
{
//creating a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
//define minutes/seconds/mseconds
var minutes:String = String(time.minutes);
var seconds:String = String(time.seconds);
var miliseconds:String = String(Math.round(time.milliseconds)/100);
//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+minutes : minutes;
seconds = (seconds.length != 2) ? '0'+seconds : seconds;
//display elapsed time on in a textfield on stage
timerDisplay.text = minutes + ":" + seconds;
}
function addCharacter():void
{
trace("Adding the character, Dave")
//set the initial values
var myBorder:Rectangle = new Rectangle(355,145,395,285);
var myXY:Array = [355,430];
var myChar:int = Math.ceil(Math.random() * 3);
var myKeys:Array = [37,39,38,40];
var myDistance:int = 7;
// create and add a new player object to the stage
daveMC = new Character(myBorder,myXY,myKeys,myChar,myDistance);
addChild(daveMC);
}
function addBots():void
{
trace("Adding the bots..");
// set the initial values (adapt to suit your game)
var myBorder:Rectangle = new Rectangle(355,145,395,285);
var myMaxBots:int = 5;// simulation
// add bots one at a time via a loop
for (var i:int = 0; i < myMaxBots; i++)
{
// create a new bot object and name it
var thisBot:Bot = new Bot(myBorder, daveMC);
thisBot.name = "bot" + i;
cGameObjs.push(thisBot);
// add it to the stage
addChild(thisBot);
}
}
function addItems():void
{
trace("Adding the items..");
//set the initial values
for (var i:int = 0; i < 10; i++)
{
// create a new bot object and name it
var thisItem:Item = new Item(daveMC);
thisItem.name = "item" + i;
cGameObjs.push(thisItem);
// add it to the stage
addChild(thisItem);
}
}
function updateLives(myBot:MovieClip):void
{
// update the player's LIVES and score
pLives--;
pEvilScore -= 30;
var myIndex:int = cGameObjs.indexOf(myBot);
cGameObjs.splice(myIndex,1);
// check for a LOST GAME
if (pLives > 0)
{
updateScores();
}
else
{
gameOver(false);
}
}
function updateItems(myItem:MovieClip):void
{
// update the player's LIVES and score
pItems--;
pEvilScore += 20;
var myIndex:int = cGameObjs.indexOf(myItem);
cGameObjs.splice(myIndex,1);
// check for a LOST GAME
if (pItems > 0)
{
updateScores();
}
else
{
gameOver(true);
}
}
function gameOver(myFlag:Boolean):void
{
updateScores();
if (myFlag)
{
// player wins
msgDisplay.text = "YAY! PAPPLE FOR \nEVERYBODY!";
removeLeftovers();
evilWinLose.text = "Weee!! We've got papples for Gru! \nYour Score: " + pEvilScore;
}
else
{
// player loses
msgDisplay.text = "OH NO! NOT \nENOUGH PAPPLES";
removeLeftovers();
evilWinLose.text = "Boo!! Not enough papples for Gru! \nYour Score: " + pEvilScore;
}
timerDisplay.text = "";
removeChild(daveMC);
evilGameOverMC.visible = true;
evilWinLose.visible = true;
toMenuBtn.visible = true;
playAgainBtn.visible = true;
toMenuBtn.addEventListener(MouseEvent.CLICK, Click_backtoMain);
playAgainBtn.addEventListener(MouseEvent.CLICK, backToEvil);
}
function updateScores():void
{
scoreDisplay.text = "" + pEvilScore;
livesDisplay.text = pLives + " lives";
msgDisplay.text = pItems + " papples more to \ncollect..";
}
function removeLeftovers():void
{
// check each BOT/ITEM in array
for each (var myObj in cGameObjs)
{
myObj.hasHitMe();
myObj = null;
}
}
function backToEvil(event:MouseEvent):void
{
pEvilScore = 0;
pLives = 3;
pItems = 3;
gotoAndStop("menu");
gotoAndStop("evil");
}
Anyone can help me out with this? Thank you alot! :)
Replace your toTimeCode function code by :
function toTimeCode(milliseconds:int): void
{
trace(1);
//creating a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
trace(2);
//define minutes/seconds/mseconds
var minutes:String = String(time.minutes);
trace(3);
var seconds:String = String(time.seconds);
trace(4);
var miliseconds:String = String(Math.round(time.milliseconds)/100);
trace(5);
//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+minutes : minutes;
trace(6);
seconds = (seconds.length != 2) ? '0'+seconds : seconds;
trace(7);
//display elapsed time on in a textfield on stage
timerDisplay.text = minutes + ":" + seconds;
trace(8);
}
Please, change the timerDisplay line to this one... The problem will be in the toTimeCode method. The error say that you are trying to call a method from a var wich is not (yet) an object...
if(null != timerDisplay)
timerDisplay.text = minutes + ":" + seconds;
You have to find an object wich is null! Add this :
function toTimeCode(milliseconds:int): void
{
//creating a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
trace("Time: " + time);

error while converting AS2 starfield code to AS3

I've tried to convert a nice AS2 script for starfirld effect to AS3 But i'm still getting strange errors
would really appreciate if any one could help me understand what am i doing wrong
here is the original AS2 code:
var stars = 100;
var maxSpeed = 16;
var minSpeed = 2;
var i = 0;
while (i < stars)
{
var mc = this.attachMovie("star", "star" + i, i);
mc._x = random(Stage.width);
mc._y = random(Stage.height);
mc.speed = random(maxSpeed - minSpeed) + minSpeed;
var size = random(2) + 6.000000E-001 * random(4);
mc._width = size;
mc._height = size;
++i;
} // end while
this.onEnterFrame = function ()
{
for (var _loc3 = 0; _loc3 < stars; ++_loc3)
{
var _loc2 = this["star" + _loc3];
if (_loc2._y > 0)
{
_loc2._y = _loc2._y - _loc2.speed;
continue;
} // end if
_loc2._y = Stage.height;
_loc2.speed = random(maxSpeed - minSpeed) + minSpeed;
_loc2._x = random(Stage.width);
} // end of for
};
and here is my AS3 version:
import flash.events.Event;
import flash.events.MouseEvent;
function starField():void
{
var stars:int = 100;
var maxSpeed:int = 16;
var minSpeed:int = 2;
var i:int = 0;
while (i < stars)
{
var mc = new Star();
addChild(mc)
mc._x = Math.random()(stage.stageWidth);
mc._y = Math.random()(stage.stageHeight);
mc.speed = Math.random()(maxSpeed - minSpeed) + minSpeed;
var size = Math.random()(2) + 6.000000E-001 * Math.random()(4);
mc._width = size;
mc._height = size;
++i;
} // end while
}
addEventListener(Event.ENTER_FRAME, update);
function update(_e:Event):void
{
for (var _loc3 = 0; _loc3 < 100; ++_loc3)
{
var _loc2 = this["star" + _loc3];
if (_loc2._y > 0)
{
_loc2._y = _loc2._y - _loc2.speed;
continue;
} // end if
_loc2._y = stage.stageHeight;
_loc2.speed = Math.random()(maxSpeed - minSpeed) + minSpeed;
_loc2._x = Math.random()(stage.stageWidth);
} // end of for
};
the error message I'm getting is: "TypeError: Error #1010: A term is undefined and has no properties. at _fla::MainTimeline/update()"
I understand it has a problem with the 'update' function but I'm net sure which term it refer to?
I'll bet a can of juice here is your problem:
var _loc2 = this["star" + _loc3];
put these into an associative array and access them from there.
#Discipol is right.
Just wanted to add a few more notes:
You can also use the display list to get the movie clip by name:
var _loc2:MovieClip = MovieClip(getChildByName("star" + _loc3));
You've got untyped variables and your are relying on MovieClip as a dynamic class to add properties (such as speed) at runtime. For a really simple project the impact is barely noticeable, but on the long run, for bigger projects, it's worth extending Sprite if you don't use the timeline and add the properties you need:
package {
import flash.display.Sprite;
import flash.events.Event;
public class Star extends Sprite {
private var speed:Number;
private var minSpeed:Number;
private var maxSpeed:Number;
public function Star(min:Number,max:Number) {
minSpeed = min;
maxSpeed = max;
var size = (Math.random()*2) + 1.82211880039 * (Math.random()*4);
width = size;
height = size;
this.addEventListener(Event.ADDED_TO_STAGE,reset);
}
private function reset(e:Event = null):void{
speed = (Math.random() * (maxSpeed-minSpeed)) + minSpeed;
x = Math.random() * stage.stageWidth;
if(e != null) y = Math.random() * stage.stageHeight;//initialized from added to stage event
else y = stage.stageHeight;//otherwise reset while updating
}
public function update():void{
if (y > 0) y -= speed;
else reset();
}
}
}
and the rest of the code would be as simple as:
var stars:int = 100;
var starClips:Vector.<Star> = new Vector.<Star>(stars,true);//a typed fixed vector is faster than a dynamically resizable untyped Array
for(var i:int = 0 ; i < stars; i++) starClips[i] = addChild(new Star(16,2)) as Star;
this.addEventListener(Event.ENTER_FRAME,updateStars);
function updateStars(e:Event):void{
for(var i:int = 0 ; i < stars; i++) starClips[i].update();
}

Action Script 3. How to remember last object x coordinates

I'm creating a flash game where objects are falling from the sky and the player needs to destroy them by clicking on them. But I have a problem, sometimes they spawning one on top of each other.
Here is an example what I mean:
Objects should be spawned near other, but not one on other.
Here is my constant vars:
public static const GRAVITY:Number = 3;
public static const HIT_TOLERANCE:Number = 50;
//Powerup
public static const APPLE_END_Y:Number = 640;
public static const APPLE_SPAWN_CHANCE:Number = 0.02; //per frame per second
public static const APPLE_START_Y:Number = 110;
public static const APPLE_SPAWN_START_X:Number = 50;
public static const APPLE_SPAWN_END_X:Number = 500;
//Scoring
public static const PLAYER_START_SCORE:Number = 0;
public static const SCORE_PER_APPLE:Number = 10;
Here is part of code where objects spawning:
private function update(evt:Event)
{
//Spawn new apples
if (Math.random() < randomChance)
{
//spawn x coordinates
var newPirmas = new Pirmas();
newPirmas.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newAntras = new Antras();
newAntras.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newTrecias = new Trecias();
newTrecias.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newApple = new Apple();
newApple.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
//spawn y coordinates
newPirmas.y = C.APPLE_START_Y;
newAntras.y = C.APPLE_START_Y;
newTrecias.y = C.APPLE_START_Y;
newApple.y = C.APPLE_START_Y;
newPirmas.addEventListener(MouseEvent.CLICK, onClick);
newAntras.addEventListener(MouseEvent.CLICK, onClick);
newTrecias.addEventListener(MouseEvent.CLICK, onClick);
newApple.addEventListener(MouseEvent.CLICK, onClick);
itemsToSpawn.push(newPirmas, newAntras, newTrecias, newApple);
}
}
As someone said: As for making sure they don't overlap, you can keep a history of their spawn points, and change how you get their random X value. Just iterate through the array of previous X values, and make sure the new one isn't within (oldX + (width/2)).
But I can't make It successfully, could you help me with keeping history of their spawn points? Thank you very much.
var t:Array = [];
t[0] = [APPLE_SPAWN_START_X, APPLE_SPAWN_END_X + APPLE_WIDTH/2];
t will keep the available intervals the you can generate new apple.
In the start time, there is no apple, and the t has only one interval, the starX of the interval is APPLE_SPAWN_START_X, the endX of the interval is APPLE_SPAWN_END_X + APP_WIDTH/2.
where you want to generate a new apple, you would find a availble interval in t, if we find the interval as mInterval(the interval could put in the apple, means endX - starX >= APPLE_WIDTH), then we could generate your new apple.
We just need to change the lines in you update function like
newPirmas.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
Instead
newPirmas.x = mInterval[0] + Math.random()*APPLE_WIDTH;
When we set newPirmas.x, we have break the mInterval and generate two new interval,
the values are [mInterval[0],newPirmas.x] and []newPirmas.x + APPLE_WIDTH, mInterval[0]],
so we need to delete the mInterval in t and put the two new intervals into t.
/**
*
* #return index of available interval in target array
*/
public static function findAvailInterval(target:Array, appleWidth:int):int {
if (target == null || target.length == 0) {
return -1;
}
var endX:int = 0;
var startX:int = 0;
var length:int = target.length;
for (var i:int = 0; i < length; i++) {
var temp:Array = target[i] as Array;
if (temp == null || temp.length < 2) {
return -1;
}
startX = temp[0];
endX = temp[1];
var intervalWidth:int = endX - startX;//the interval width
if (intervalWidth >= appleWidth) {//find an available one
return i;
}
}
return -1;
}
public static function breakInterval(target:Array, appleWidth:int, index:int):int {
var temp:Array = target[index];
var startX:int = temp[0];
var endX:int = temp[1];
var width:int = endX - startX;
var availableNewXRange:int = width - appleWidth;//the appleā€˜s max x, and the min x is startX
//random a position
var appleX:int = startX + availableNewXRange*Math.random();
var leftInterval:Array = [startX, appleX];//the left interval of apple
var rightInterval:Array = [appleX+appleWidth, endX];//the right interval of apple
//delete temp
target.splice(index, 1);
if (isAvailableInterval(leftInterval, appleWidth)) {
target.push(leftInterval);
}
if (isAvailableInterval(rightInterval, appleWidth)) {
target.push(rightInterval);
} else {
trace("vvv");
}
return appleX;
}
private static function isAvailableInterval(interval:Array, appleWidth:int):Boolean {
if (interval == null || interval.length < 2) {
return false;
}
return (interval[1] - interval[0]) >= appleWidth;
}
Put the three functions into a class A
var target:Array = [[0, 1000]];
var appWidth:int = 80;
for (var i:int = 0; i < 4; i++) {
var index:int = A.findAvailInterval(target, appWidth);
if (index != -1) {
var interval:Array = target[index];
RR.breakInterval(target, appWidth, index);
trace(interval);
}
}

AS3 creating dynamic Loader Names in a loop

EDITED for clarity: I want to load all kinds of images from an external url in a for loop.
I want to call them in a loop and when it's over I start the loop again. however I don't want to call them again with an "http request" rather I would like to loop through the loaded images over and over again.
Is it possible to create a dynamic Loader name in a loop?
Here is the code example:
var Count = 0;
// Loop Begins
var Count:Loader = new Loader();
Count.load(new URLRequest("myurl");
addChild(Count);
Count++;
// End Loop
Another example would be to have a NAME and just add the number on the end. But how
var Count = 0;
// Loop Begins
var MyName+Count:Loader = new Loader();
MyName+Count.load(new URLRequest("myurl");
addChild(MyName+Count);
Count++;
// End Loop
IN SHORT:
I want to load a bunch of images into an Array and loop through the loaded images by calling them later.
Thanks so much!
CASE1 code is how to load images in Sequence.
CASE2 code is how to load images in Synchronized.
First, the URL you want to import all images must be named sequentially.
for example Must be in the following format:
www.myURL.com/img0.jpg
www.myURL.com/img1.jpg
www.myURL.com/img2.jpg
www.myURL.com/img3.jpg
www.myURL.com/img4.jpg
www.myURL.com/img5.jpg
.
.
.
Try the code below, just a test.
CASE1
var imgLoader:Loader;
var imgRequest:URLRequest;
var count:int = -1;
const TOTAL_COUNT:int = 10;
var imgBox:Array = [];
var isCounting:Boolean;
function loadImage():void
{
count ++;
isCounting = true;
imgLoader = new Loader();
imgRequest = new URLRequest();
imgRequest.url = "www.myURL.com/img" + count +".jpg";
imgLoader.load(imgRequest);
imgLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, unloadedImg);
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadedImg);
if(count == TOTAL_COUNT)
{
isCounting = false;
count = -1;
}
}
function onLoadedImg(e:Event):void
{
imgLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadedImg);
var bmp:Bitmap = e.currentTarget.content;
bmp.x = Math.random() * width;
bmp.y = Math.random() * height;
bmp.width = 100;
bmp.height = 100;
this.addChild(bmp);
imgBox.push(bmp);
if( isCounting == false)
{
return;
}
loadImage();
}
function unloadedImg(e:IOErrorEvent):void
{
imgLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, unloadedImg);
trace("load Failed:" + e);
}
loadImage();
CASE2
var imgLoader:Loader;
var imgRequest:URLRequest;
const TOTAL_COUNT:int = 10;
var imgBox:Array = [];
function loadImage2():void
{
for(var i:int = 0; i<TOTAL_COUNT; i++)
{
imgLoader = new Loader();
imgRequest = new URLRequest();
imgRequest.url = "www.myURL.com/img" + i +".jpg";
imgLoader.load(imgRequest);
imgLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, unloadedImg);
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadedImg);
}
}
function onLoadedImg(e:Event):void
{
imgLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadedImg);
var bmp:Bitmap = e.currentTarget.content;
bmp.x = Math.random() * width;
bmp.y = Math.random() * height;
bmp.width = 100;
bmp.height = 100;
this.addChild(bmp);
imgBox.push(bmp);
}
function unloadedImg(e:IOErrorEvent):void
{
imgLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, unloadedImg);
trace("load Failed:" + e);
}
loadImage2();
If you want access loaded Image. refer a following code. If you do not put them in an array can not be accessed in the future.
for(var int:i=0; i<TOTAL_COUNT; i++)
{
var bitmap:Bitmap = imgBox[i] as Bitmap;
trace("index: " + i + "x: " + bitmap.x + "y: " + bitmap.y, "width: " + bitmap.width + "height: " + bitmap.height);
}
Now that we're on the same page:
var imgArray:Array = new Array;
var totalImages:int = 42;
var totalLoaded:int = 0;
var loaded:Boolean = false;
function loadImages():void{
for(var count:int = 0; count < totalImages; count++){
var image:Loader = new Loader();
image.load(new URLRequest("image" + i + ".jpg");
image.addEventListener(Event.COMPLETE, loaded);
imgArray.push(image);
}
}
function loaded(e:Event):void{
totalLoaded++;
if (totalLoaded == totalImages){
loaded = true;
}
}
function displayImages():void{
if (loaded){
for(var i:int = 0; i < imgArray.length(); i++){
addChild(imgArray[i]);
}
}
}

Flash CS5 AS3 Can not get Flashvars

I am new to fairly new to AS3 and I have found myself needing to extend a fla. that was written by a 3rd party.
The goal is to access flashvars but for the life of me can not get it to work...been at it for days learning..
the fla I am working with is code on timeline with 2 frames. the movieclip runs to frame 2 ans stops.
On frame 2 is where I require the use of the flashvar.
I have built a simple example that will populate a textbox on frame two that works fine.
frame 1
var my_var:String = new String();
my_var = root.loaderInfo.parameters.uploadId;
frame 2
my_txt.text = my_var;
stop();
However when I use the same approach on my 3rd party fla I get NULL output. I am not using any TLF text either (I think).
I don't understand why it works in one case but not the other. I am thinking it might have to do with conflict with the surrounding code but I don't know enough about AS to track it down. Any help on this would be greatly appreciated.
frame 1
import net.bizmodules.uvg.loading;
stop();
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.showDefaultContextMenu = false;
stage.quality = StageQuality.BEST;
function RandomValue()
{
var d = new Date();
return String(d.getDate()) + String(d.getHours()) + String(d.getMinutes()) + String(d.getSeconds());
}
var my_var:String;
my_var = root.loaderInfo.parameters.uploadId;
var userId;
var albums:Object;
var resource:Object;
var strUploadPage:String;
if (root.loaderInfo.parameters.uploadPage != undefined)
strUploadPage = root.loaderInfo.parameters.uploadPage;
else
strUploadPage = "http://localhost/dnn450/desktopmodules/ultramediagallery/flashuploadpage.aspx?PortalId=0&ModuleId=455";
if (strUploadPage.indexOf("?") > 0)
strUploadPage += "&";
else
strUploadPage += "?";
strUploadPage += "action=loadAlbums&seed=" + RandomValue();
trace(strUploadPage);
var myLoading:MovieClip = new loading();
myLoading.x = (stage.stageWidth - myLoading.width) / 2;
myLoading.y = (stage.stageHeight - myLoading.height) / 2;
addChild(myLoading);
var myRequest:URLRequest = new URLRequest(strUploadPage);
var myLoader:URLLoader = new URLLoader(myRequest);
myLoader.addEventListener(Event.COMPLETE, xmlLoaded);
function xmlLoaded(evtObj:Event)
{
myLoader.removeEventListener(Event.COMPLETE, xmlLoaded);
try
{
var xDoc:XMLDocument = new XMLDocument();
xDoc.ignoreWhite = true;
var xml:XML = XML(myLoader.data);
xDoc.parseXML(xml.toXMLString());
userId=xDoc.firstChild.attributes.userId;
if (userId < 0)
{
removeChild(myLoading);
txtError.text = "Please ensure you are logged in";
return;
}
if(xDoc.firstChild.childNodes.length > 0)
{
albums = xDoc.firstChild.childNodes[0].childNodes;
resource = xDoc.firstChild.childNodes[1].attributes;
}
else
{
removeChild(myLoading);
txtError.text = xDoc.firstChild.attributes.error;
return;
}
play();
}
catch(e:Error)
{
removeChild(myLoading);
txtError.text = e + "\n\nPlease check your Event Viewer to find out detailed error message and contact service#bizmodules.net";
}
}
frame 2
import net.bizmodules.upg.Alert;
stop();
removeChild(myLoading);
initialize();
function initialize()
{
Alert.init(stage);
upload.addVar("userId",userId);
lstAlbums.dropdown.rowHeight = 24;
loadAlbums(0, albums);
var my_so:SharedObject = SharedObject.getLocal("UPGUpload");
var lastAlbum = my_so.data.lastAlbum * 1;
var foundLastAlbum = false;
if (lastAlbum > 0)
{
for (var i:int = 0; i< lstAlbums.length; i++)
{
if (lstAlbums.getItemAt(i).data == lastAlbum)
{
trace("find previous album");
foundLastAlbum = true;
lstAlbums.selectedIndex = i;
break;
}
}
}
if (!foundLastAlbum)
{
lstAlbums.selectedIndex = lstAlbums.length - 1;
}
albums_change(null);
lstAlbums.addEventListener("change", albums_change);
lstAlbums.setStyle("backgroundColor", 0x504C4B);
lstAlbums.dropdown.setStyle("backgroundColor", 0x504C4B);
lstAlbums.setStyle("themeColor", 0x1F90AE);
lstAlbums.setStyle("color", 0xC4C0BF);
lstAlbums.setStyle("textSelectedColor", 0xC4C0BF);
lstAlbums.setStyle("textRollOverColor", 0xC4C0BF);
lstAlbums.setStyle("alternatingRowColors", [0x504C4B, 0x504C4B]);
lstAlbums.setStyle("borderStyle", 'none');
}
my_txt.text = "hello" + " " + my_var;
function loadAlbums(level:int, xml:Object)
{
var prefix = " ".substring(0, level * 4);;
for (var i:int = 0;i<xml.length;i++)
{
var itemValue = xml[i].attributes.itemid;
if (xml[i].childNodes.length > 0)
itemValue *= -1;
lstAlbums.addItem({data: itemValue, label: prefix + xml[i].attributes.name});
if (xml[i].childNodes.length > 0)
{
loadAlbums(level + 1, xml[i].childNodes);
}
}
}
function albums_change(e)
{
var albumId = lstAlbums.getItemAt(lstAlbums.selectedIndex).data;
upload.set_albumId(albumId);
if (albumId > 0)
{
var my_so:SharedObject = SharedObject.getLocal("UPGUpload");
my_so.data.lastAlbum = albumId;
}
else
{
Alert.show("The album you choosed is invalid", null, 0xEAEAEA, 0x000000);
}
}
private var flashVarObj:Object = new Object;
flashVarObj=LoaderInfo(this.loaderInfo).parameters;
var my_var:String = new String();
my_var = flashVarObj.uploadIdd;