actionscript 3 synchronous loader - actionscript-3

I have typical situation where big loop is loading lots of images and its done asynchronous which make browser to frees during loading and I want to make it synchronous but having big trouble doing it. I found this class synchronous loader and it work great but you cant add mouse event listener to loader. Here is sample code:
for (var i = 0; i < items.length; i++) {
item = items[i];
if(item.layer>1){
ld:Loader = new Loader();
ld.load(new URLRequest(item.url));
ld.rotation = item.rotation;
ld.x = item.x ;
ld.y = item.y;
ld.addEventListener(Event.COMPLETE, loadComplete);
ld.scaleX = item.scaleX;
ld.scaleY = item.scaleY;
ld.addEventListener(MouseEvent.MOUSE_DOWN, select);
layers_arr[item.layer].addChild(ld);
}
}
Any idea how this can be done?

like arieljake says, here is a little example on how to use it:
package
{
import com.greensock.TweenLite;
import com.greensock.events.LoaderEvent;
import com.greensock.loading.ImageLoader;
import com.greensock.loading.LoaderMax;
import com.greensock.loading.MP3Loader;
import com.greensock.loading.SWFLoader;
import com.greensock.loading.XMLLoader;
import com.greensock.loading.display.ContentDisplay;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
public class Main extends Sprite
{
public var itemUrl:String;
public var queue:LoaderMax = new LoaderMax({name:"mainQueue", onProgress:progressHandler, onComplete:completeHandler, onError:errorHandler});
public function Main()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
queue.maxConnections = 1; //Checks how much items that can be loaded at the same time
queue.append( new ImageLoader("http://www.myurl.com/myimage.jpg", {name:"photo1", estimatedBytes:2400, container:this, alpha:0,scaleMode:"proportionalInside"}) );
queue.append( new ImageLoader("http://www.myotherurl.com/awesomeimage.jpg", {name:"photo2", estimatedBytes:2400, container:this, alpha:0, scaleMode:"proportionalInside"}) );
queue.addEventListener(LoaderEvent.CHILD_COMPLETE, childCompleteHandler); //checks when a child has completed to load
queue.addEventListener(LoaderEvent.CHILD_PROGRESS, childProgressHandler); //checks the child progress
//prioritize the loader named "photo1"
LoaderMax.prioritize("photo1"); //same as LoaderMax.getLoader("photo1").prioritize();
//start loading
queue.load();
}
protected function childProgressHandler(event:LoaderEvent):void
{
var procent:Number = Math.floor(event.target.progress*100);
var targetName:String = event.target.name;
trace(procent+'% loaded of item: '+targetName);
}
protected function childCompleteHandler(event:LoaderEvent):void
{
var targetName:String = event.target.name;
trace(targetName+' is loaded!');
}
private function completeHandler(event:LoaderEvent):void {
var objects:Array = event.currentTarget.content;
for(var i:uint=0; i < objects.length; i++)
{
var image:ContentDisplay = LoaderMax.getContent(objects[i].name);
TweenLite.to(image, 1, {alpha:1, y:100});
}
trace(event.target + " is complete!");
}
private function errorHandler(event:LoaderEvent):void {
trace("error occured with " + event.target + ": " + event.text);
}
}
}

Check this out: http://www.greensock.com/loadermax/
Let's you specify max number of simultaneous loaders

Related

How To Load Image Though URL in action script 3.0

I have tested the code in action script 2.0 . it is working great but it does not support GIF so i want it write in action script 3.0.
But i have no idea in this.
var current_loader: Number = 1;
import flash.geom.*;
var current_img: Number = 0;
this.createEmptyMovieClip('img_01', 999);
this.createEmptyMovieClip('img_02', 998);
var loader: MovieClipLoader = new MovieClipLoader();
var listener: Object = new Object();
listener.onLoadComplete = function (target_mc: MovieClip) {
if (target_mc._name == 'img_01') {
img_02._visible = false;
} else {
img_01._visible = false;
}
progress_bar.visible = true;
current_loader.opaqueBackground = 0xFF0000;
};
var interval: Number = setInterval(load_image, 1000);
function load_image() {
loader.addListener(listener);
}
loader.loadClip("http://google/Example3", current_loader);
current_loader = current_loader == 1 ? 2 : 1;
current_img = current_img == images.length - 1 ? 0 : current_img + 1;
}
Very simple in as3:
open Flash IDE, create new .fla file, select first frame, open 'actions (f9)' copy code.
Of course in AS3 it's better to use classes to put your code in.
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.net.URLRequest;
var imageLoader:Loader = new Loader();
var request:URLRequest = new URLRequest("http://dummyimage.com/600x400/e000e0/fff.gif");
imageLoader.load(request);
addChild (imageLoader);
// and all possible listeners
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
imageLoader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
imageLoader.contentLoaderInfo.addEventListener(Event.INIT, initHandler);
imageLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
imageLoader.contentLoaderInfo.addEventListener(Event.OPEN, openHandler);
imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
function completeHandler(event:Event):void {
trace("completeHandler: " + event);
}
function httpStatusHandler(event:HTTPStatusEvent):void {
trace("httpStatusHandler: " + event);
}
function initHandler(event:Event):void {
trace("initHandler: " + event);
}
function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event);
}
function openHandler(event:Event):void {
trace("openHandler: " + event);
}
function progressHandler(event:ProgressEvent):void {
trace("progressHandler: bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);
}
see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/Loader.html#includeExamplesSummary
There are simpler ways using straight as3 but this a robust way to load may file types with lots of great documentation. https://greensock.com/LoaderMax-AS3
i did like this .And its Working Perfectly.i think it is the simplest .
package
{
import flash.display.Loader;
import flash.display.Sprite;
import flash.net.URLRequest;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
public class Example extends Sprite {
public function Example() {
var myTimer:Timer = new Timer(1000);// 1 second
myTimer.addEventListener(TimerEvent.TIMER,runMany);
myTimer.start();
function runMany(e:TimerEvent):void {
var loader:Loader=new Loader();
var url:String= "http://Google.Example3.com/latimage.php";
loader.load(new URLRequest(url));
addChild(loader);
}
}
}
}

Actionscript 3: Error #1009: Cannot access a property or method of a null object reference. (parent)

This is a bit difficult to explain, but I will try.
In my Main() class, let's say I have the main movieclip (bg_image) being created, and also some lines that create an instance of another class. (look at the code below)
var route = Route(Airport.return_Route);
This route instance, is then purposed to dynamically add sprite-childs to the main background from the Main() class.
I have tried to to this with the following line:
new_flight = new Flight(coordinates)
Main.bg_image.addChild(new_flight);
This seem to work pretty fine. Let's switch focus to the new_flight instance. At the Flight class, this line trace(this.parent) would return "[object Image]".I would consider this successful so far since my intention is to add the new_flight as child to bg_image, which I guess is an "object image".
The problem, however, occurs when trying to delete the "new_flight"-instance. Obviously the ideal way of doing this would be through bg_image with removeChild.
But, when my script reaches this line: Main.bg_image.removeChild(this), my script stops and returns ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller., at that line. I have also tried replacing Main.bg_image.removeChild(this) with this.parent.removeChild(this), with no luck.
I think the solution may be to use some sort of "EventDispatching"-method. But I haven't fully understood this concept yet...
The code follows. Please help. I have no idea how to make this work...
Main class:
package
{
import flash.display.MovieClip;
import flash.utils.Dictionary;
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.text.TextField;
import fl.controls.Button;
import flash.display.DisplayObject;
import Airport;
public class Main extends Sprite
{
// ------------------------
// Buttons
public var create_new_route;
public var confirm_new_route;
// images
public static var bg_image:MovieClip;
public var airport:MovieClip;
//-------------------------------
public var routeArray:Array;
public static var airportDict:Dictionary = new Dictionary();
public static var collectedAirportArray:Array = new Array();
public function Main()
{
addEventListener(Event.ADDED_TO_STAGE, init);
create_new_route = new Button();
create_new_route.label = "Create new route";
create_new_route.x = 220;
create_new_route.y = 580;
this.addChild(create_new_route)
create_new_route.addEventListener(MouseEvent.CLICK, new_route)
confirm_new_route = new Button();
confirm_new_route.label = "Confirm route";
confirm_new_route.x = 220;
confirm_new_route.y = 610;
this.addChild(confirm_new_route)
confirm_new_route.addEventListener(MouseEvent.CLICK, confirm_route)
}
public function init(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
bg_image = new Image();
addChild(bg_image);
S_USA["x"] = 180.7;
S_USA["y"] = 149.9;
S_USA["bynavn"] = "New York";
S_Norway["x"] = 423.7;
S_Norway["y"] = 76.4;
S_Norway["bynavn"] = "Oslo";
S_South_Africa["x"] = -26;
S_South_Africa["y"] = 146;
S_South_Africa["bynavn"] = "Cape Town";
S_Brazil["x"] = 226;
S_Brazil["y"] = 431.95;
S_Brazil["bynavn"] = "Rio de Janeiro";
S_France["x"] = 459.1;
S_France["y"] = 403.9;
S_France["bynavn"] = "Paris";
S_China["x"] = 716.2;
S_China["y"] = 143.3;
S_China["bynavn"] = "Beijing";
S_Australia["x"] = 809.35;
S_Australia["y"] = 414.95;
S_Australia["bynavn"] = "Sydney";
// ----------------------------------------------------
airportDict["USA"] = S_USA;
airportDict["Norway"] = S_Norway;
airportDict["South Africa"] = S_South_Africa;
airportDict["Brazil"] = S_Brazil;
airportDict["France"] = S_France;
airportDict["China"] = S_China;
airportDict["Australia"] = S_Australia;
for (var k:Object in airportDict)
{
var value = airportDict[k];
var key = k;
startList.addItem({label:key, data:key});
sluttList.addItem({label:key, data:key});
var airport:Airport = new Airport(key,airportDict[key]["bynavn"]);
airport.koordinater(airportDict[key]["x"], airportDict[key]["y"]);
collectedAirportArray.push(airport);
airport.scaleY = minScale;
airport.scaleX = minScale;
bg_image.addChild(airport);
}
// --------------------------------------------
// --------------------------------------------
// -----------------------------------------------
}
private function new_route(evt:MouseEvent):void
{
Airport.ROUTING = true;
}
public function confirm_route(evt:MouseEvent):void
{
Airport.ROUTING = false;
trace(Airport.return_ROUTE);
var route = new Route(Airport.return_ROUTE); // ***
this.addChild(route); // **
Airport.return_ROUTE = new Array();
}
}
}
Airport class:
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.SimpleButton;
import flash.display.Stage;
import flash.text.TextField;
import flash.text.TextFormat;
import flashx.textLayout.formats.Float;
public class Airport extends MovieClip
{
public static var ROUTING = false;
public static var return_ROUTE:Array = new Array();
//-----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
protected var navn:String;
protected var bynavn:String;
// ----------------------------------------------------------------------------
public function Airport(navninput, bynavninput)
{
this.bynavn = bynavninput;
this.navn = navninput;
this.addEventListener(MouseEvent.CLICK, clickHandler);
this.addEventListener(MouseEvent.MOUSE_OVER, hoverHandler);
}
public function zoomHandler():void
{
trace("testing complete");
}
public function koordinater(xc, yc)
{
this.x = (xc);
this.y = (yc);
}
private function clickHandler(evt:MouseEvent):void
{
trace(ROUTING)
if (ROUTING == true)
{
return_ROUTE.push([this.x, this.y])
}
}
private function hoverHandler(evt:MouseEvent):void
{
if (ROUTING == true)
{
this.alpha = 60;
this.width = 2*this.width;
this.height = 2*this.height;
this.addEventListener(MouseEvent.MOUSE_OUT, awayHandler);
}
}
private function awayHandler(evt:MouseEvent):void
{
this.width = 13;
this.height = 13;
}
}
}
Route class
package
{
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.display.MovieClip;
import Main;
public class Route
{
public var income:Number;
public var routePoints:Array;
private var routeTimer:Timer;
private var new_flight:Flight;
public function Route(route_array:Array)
{
this.routePoints = route_array
routeTimer = new Timer(2000);// 2 second
routeTimer.addEventListener(TimerEvent.TIMER, route_function);
routeTimer.start();
}
private function route_function(event:TimerEvent):void
{
for (var counter:uint = 0; counter < routePoints.length - 1; counter ++)
{
trace("Coords: ", routePoints[counter][0],routePoints[counter][1],routePoints[counter + 1][0],routePoints[counter + 1][1]);
new_flight = new Flight(routePoints[counter][0],routePoints[counter][1],routePoints[counter + 1][0],routePoints[counter + 1][1]);
Main.bg_image.addChild(new_flight);
var checkTimer:Timer = new Timer(15);// 1 second
checkTimer.addEventListener(TimerEvent.TIMER, check_function);
checkTimer.start();
function check_function(event:TimerEvent):void
{
if (new_flight.finished = true)
{
checkTimer.stop();
}
}
}
}
}
}
Flight class
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.SimpleButton;
import flash.display.Stage;
import flash.events.TimerEvent;
import flash.utils.Timer;
import fl.controls.Button;
import flash.display.DisplayObject;
public class Flight extends MovieClip
{
public static var speed:uint = 1
public var finished:Boolean = false;
protected var absvector:Number;
protected var vector:Array;
protected var myTimer:Timer;
//protected var parentContainer:MovieClip;
protected var utgangspunkt_x;
protected var utgangspunkt_y;
protected var destinasjon_x;
protected var destinasjon_y;
protected var vector_x;
protected var vector_y;
public function Flight(utgangspunkt_x, utgangspunkt_y, destinasjon_x, destinasjon_y):void
{
addEventListener(Event.ADDED_TO_STAGE, init);
this.utgangspunkt_x = utgangspunkt_x;
this.utgangspunkt_y = utgangspunkt_y;
this.x = utgangspunkt_x;
this.y = utgangspunkt_y;
this.destinasjon_x = destinasjon_x + 10;
this.destinasjon_y = destinasjon_y + 10;
this.vector_x = Math.abs(this.destinasjon_x-this.utgangspunkt_x);
this.vector_y = Math.abs(this.destinasjon_y-this.utgangspunkt_y);
this.height = 20;
this.width = 20;
}
public function init(evt:Event):void
{
trace(this.parent)
if (utgangspunkt_x < destinasjon_x)
{
this.rotation = -(Math.atan((utgangspunkt_y-destinasjon_y)/(destinasjon_x-utgangspunkt_x)))/(Math.PI)*180;
}
else
{
this.rotation = 180-(Math.atan((utgangspunkt_y-destinasjon_y)/(destinasjon_x-utgangspunkt_x)))/(Math.PI)*180;
}
absvector = Math.sqrt(Math.pow((destinasjon_x - utgangspunkt_x),2) + Math.pow((utgangspunkt_y - destinasjon_y),2));
vector = [(destinasjon_x - utgangspunkt_x) / absvector,(utgangspunkt_y - destinasjon_y) / absvector];
stage.addEventListener(Event.ENTER_FRAME, movement)
}
private function movement(evt:Event):void
{
if (this.vector_x > this.vector_y)
{
if (destinasjon_x>utgangspunkt_x)
{
if (this.x < destinasjon_x)
{
this.x += speed*vector[0];
this.y -= speed*vector[1];
}
else
{
finished = true
Main.bg_image.removeChild(this)
}
}
else if (destinasjon_x<utgangspunkt_x)
{
if (this.x > destinasjon_x)
{
this.x += speed*vector[0];
this.y -= speed*vector[1];
}
else
{
finished = true
Main.bg_image.removeChild(this)
}
}
}
else
{
if (destinasjon_y>utgangspunkt_y)
{
if (this.y < destinasjon_y)
{
this.x += speed*vector[0];
this.y -= speed*vector[1];
}
else
{
finished = true
Main.bg_image.removeChild(this)
}
}
else if (destinasjon_y<utgangspunkt_y)
{
if (this.y > destinasjon_y)
{
this.x += speed*vector[0];
this.y -= speed*vector[1];
}
else
{
finished = true
Main.bg_image.removeChild(this)
}
}
}
}
}
}
I am confused what your asking and what your trying to do, but I will give it my best shot.
this.addchild(new_class2)
This line adds your object to the display list. Adding another object to the display is done the same way you added the first. Flash adds objects in the sequentially, so the objects you want in the back need to be declared and added first.
This is probably what you want:
var new_flight:Flight = new Flight();
this.addchild(new_flight);
Also you forgot your type declaration for Class2:
var new_class2:Class2 = new Class2();
Try replacing:
Main.bg_image.addChild(new_flight);
with
Main(this.parent).bg_image.addChild(new_flight);
... assuming the 'main' class you refer to is infact named 'Main' and it has a named instance called 'bg_image'
Please leave a comment if it works, I can explain in more detail what is actually happening here.
Why you are adding new_flight to bg_image?
Anyway, if you are adding new_flight to bg_image, then you have bg_image already declared as public static (which I do not recommend),
Try removing the flight in your Flight class it-self like so,
Main.bg_image.removeChild(this) // *
You can also use Event Dispatching instead of declaring bg_image as static.
If you want to remove flight then dispatch event from Flight class to Route class and there you again dispatch event to main class.
And, inside main class capture this event and access the MovieClip.

Changing the UrlLoader.load

package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.text.StyleSheet;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.text.*
import flash.net.*
public class SpeechBox extends MovieClip{
public var textLoader:URLLoader = new URLLoader();
public var box:Sprite = new Sprite();
public var nextBox:Sprite = new Sprite();
private var nextText:TextField = new TextField();
private var textBox:TextField = new TextField();
private var speechText:String;
public var _speechBoxCheck:Timer = new Timer(1000);
public var clickedNext:Boolean = false;
public function SpeechBox()
{
textLoader.addEventListener(Event.COMPLETE, onLoaded);
textBox.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownScroll);
_speechBoxCheck.addEventListener(TimerEvent.TIMER, speechBoxCheck);
_speechBoxCheck.start();
//////////////////SPEECH BOX///////////////////
box.graphics.lineStyle(3.5,0xffffff);
box.graphics.beginFill(0x003366, .35);
box.graphics.drawRoundRect(0,0,650,145,20);
box.graphics.endFill();
box.x = 100;
box.y = 450;
addChild(box);
//////////////////SPEECH TEXT///////////////////
var speechFont = new DataText();
var textFormat:TextFormat = new TextFormat();
textFormat.font = speechFont.fontName;
textFormat.align = TextFormatAlign.LEFT;
textFormat.leading = 3;
textFormat.color = 0xFFFFFF;
textFormat.size = 16;
textBox.defaultTextFormat = textFormat;
textBox.width = 620;
textBox.height = 115;
textBox.x = box.x + 14;
textBox.y = box.y + 14;
textBox.multiline = true;
textBox.wordWrap = true;
textBox.selectable = false;
addChild(textBox);
//////////////////NEXT BUTTON///////////////////
nextBox.graphics.beginFill(0x000000, 0);
nextBox.graphics.drawRect(0,0,50,30);
nextBox.graphics.endFill();
nextBox.x = box.x + 600;
nextBox.y = box.y + 115;
nextText.defaultTextFormat = textFormat;
nextText.text = "Next";
nextText.textColor = 0xffffff;
nextText.autoSize = "left";
nextText.selectable = false;
nextText.mouseEnabled = false;
nextText.x = nextBox.x + 2
nextText.y = nextBox.y + 5
nextBox.buttonMode = true;
//nextBox.mouseEnabled = true;
nextBox.addEventListener(MouseEvent.MOUSE_DOWN, clickNext);
nextBox.addEventListener(MouseEvent.MOUSE_OVER, moveOver);
nextBox.addEventListener(MouseEvent.MOUSE_OUT, moveOut);
}
function onLoaded(e:Event):void {
trace(e.target.data);
textBox.text = e.target.data;
}
function mouseDownScroll(event:MouseEvent):void
{
textBox.scrollV+=4;
textBox.addEventListener(MouseEvent.MOUSE_UP,mouseup);
}
function mouseup(event:MouseEvent):void
{
if(textBox.scrollV == textBox.maxScrollV)
{
addChild(nextBox);
addChild(nextText);
}
}
function clickNext(event:MouseEvent):void
{
trace("click");
clickedNext = true;
_speechBoxCheck.stop();
(parent as Main).onTransition.start();
textBox.scrollV = 0;
textLoader.removeEventListener(Event.COMPLETE, onLoaded);
this.parent.removeChild(this);
}
function moveOver(event:MouseEvent):void
{
nextText.textColor = 0xffcc00;
}
function moveOut(event:MouseEvent):void
{
nextText.textColor = 0xffffff;
}
///////////////////////////////////////////////////////////////
function speechBoxCheck(event:TimerEvent)
{
if ((parent as Main).introduction == true)
{
textLoader.load(new URLRequest("Texts/LV1introduction.txt"));
trace("beginning");
(parent as Main).onTransition.stop();
}
if ((parent as Main).levelNum == 1)
{
textLoader.load(new URLRequest("Texts/LV1complete.txt"));
trace("go to lv 2")
(parent as Main).onTransition.stop();
}
if ((parent as Main).levelNum == 2)
{
textLoader.load(new URLRequest("Texts/LV2complete.txt"));
trace("go to lv 3")
(parent as Main).onTransition.stop();
}
}
}
}
EDIT: When the game starts, the LV1 introduction text starts. Once the scrollV equals maxScrollV, a next buttons appears. Click that, it will delete itself and the game starts. Once you beat stage one, levelNum automatically equals 2 and I add this class again from my main document class. However, it will show the same text over and over, regardless of what level.
So does the urlLoader always stay the same? If so, how can I change it?
URLLoader can be reused to load another data with new URLRequest instance. It is completely OK to reuse same URLLoader instance to load another file. Your problem is not in URLLoader, but in logics or somewhere else. You'd better try debuggers to make sure variable level has correct value of 2.
Why are you loading text file EVERY second? It would be ok to load them only level is changed.
does this textLoader instance have event listeners attached?
:::::::::EDITED:::::::::
You are removing event Listeners from textLoader in clickNext() call. textLoader will load file, but will not run onLoaded() to update textBox.text
Your speechBoxCheck() method is doing it wrong. 1. You must make only 1 load() call in speechBox() method. Your conditionals in the method are not exclusive, and it may cause trouble when multiple load() calls are made (previous loading operation will be canceled). consider "else if" chain.
it is not recommended to do something like loading files in this fashion. Unnecessary I/O operations, especially in runtime, should be avoided. Only load files when it is needed; In this case, it is when level changes.

FLASH AS3 - Dynamicly Loaded Slideshow From Txt File

I have done a simple code for a slideshow that dynamicly loads images from a subfolder, depending on what is listet in a text file.
the code:
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Loader;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.display.Bitmap;
import flash.display.BitmapData;
public class slideshow extends MovieClip {
public var listLoader:URLLoader;
public var newImgList:Array;
public var imgX:int = 0;
public var container:MovieClip;
public function slideshow() {
container = new MovieClip();
stage.addChild(container);
listLoader = new URLLoader(new URLRequest("./slideshow.txt"));
listLoader.addEventListener(Event.COMPLETE, initImages);
}
public function initImages(event:Event):void {
var imgList:Array = listLoader.data.replace(/^\s+/,"").replace(/\s+$/,"").split(/\s+/);
newImgList = new Array();
for(var line:int = 0; line < imgList.length; line++ ) {
if(imgList[line].indexOf(".png") != -1 || imgList[line].indexOf(".jpg") != -1) {
newImgList.push(imgList[line]);
}
}
loadImage();
}
public function loadImage():void {
for(var loaderNum = 0; loaderNum < newImgList.length; loaderNum++) {
var imgLoader = new Loader();
imgLoader.load(new URLRequest("./slideshow/" + newImgList[loaderNum]));
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imgInit);
}
}
public function imgInit(event:Event):void {
var imgBmp:BitmapData = event.target.content.bitmapData;
var img:Bitmap = new Bitmap(imgBmp);
img.height = 150;
img.scaleX = img.scaleY;
img.y = 0;
img.x = imgX;
imgX = (imgX + img.width + 10);
container.addChild(img);
}
}
well actually it works fine for me except for that the images are displayed in a almost random order.
i guess the code is loading some images too slow, so some of them are added to the movieclip although they are loaded after the one that should go next.
so what i mean :
1.png is loaded
1.png is added
2.png is loaded
3.png is loaded
3.png is added
2.png is added
so my question:
is there any other propper/better way to make that slideshow load images from a textfile where just the full names of the images ( that are in a subfolder ) are listet ?
thanks for any suggestions.
g.r.
Queue your image loading to have them ordered.
Rough example:
var queue:Array = []; // Populated from your text/whatever file.
// If you want the images to load from first to last you will need
// to use queue.reverse() once you get the filenames.
/**
* Beings loading the next image in queue.
* Ignored if the queue has no remaining items.
*/
function loadNext():void
{
if(queue.length > 0)
{
var imgSrc:String = queue.pop();
var ldr:Loader = new Loader();
ldr.load(new URLRequest(imgSrc));
ldr.addEventListener(Event.COMPLETE, _done);
}
}
/**
* Called once a Loader instance has finished loading a resource.
* #param e Event.COMPLETE.
*/
function _done(e:Event):void
{
e.target.removeEventListener(Event.COMPLETE, _done);
container.addChild(e.target as DisplayObject);
// Begin loading the next image in queue.
loadNext();
}

Dispatching event doesn't fire :(

package com.fladev.background
{
//import all classes
import caurina.transitions.Tweener;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.display.StageAlign;
import flash.display.StageDisplayState;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.FullScreenEvent;
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
public class MainClass extends Sprite
{
//create variables
private var loaderMenu:Loader;
private var loaderNames:Array = new Array ();
private var loaderContents:Array = new Array ();
private var loaderSlide:Loader;
private var swfDisplayObject:DisplayObject;
private var swfComObject:Object;
private var xmlLoader:URLLoader = new URLLoader();
private var xmlSlideLoader:URLLoader = new URLLoader();
public function MainClass()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(Event.RESIZE, stageResize);
xmlLoader.addEventListener(Event.COMPLETE, showXML);
xmlLoader.load(new URLRequest("navigation.xml"));
//xmlSlideLoader.addEventListener(Event.COMPLETE, showSlideXML);
//xmlSlideLoader.load(new URLRequest("slides.xml"));
}
function showXML(e:Event):void
{
XML.ignoreWhitespace = true;
var menuBtns:XML = new XML(e.target.data);
var i:Number = 0;
for ( i = 0; i < menuBtns.navItem.length(); i++ )
{
loaderMenu = new Loader();
loaderMenu.name = menuBtns.navItem[i].name ;
loaderMenu.load(new URLRequest(menuBtns.navItem[i].swfURL));
loaderMenu.contentLoaderInfo.addEventListener(Event.COMPLETE, createSwfObjects);
}
}
private function createSwfObjects(event:Event):void
{
var swfContent = event.currentTarget.content as MovieClip ;
var swfName = event.currentTarget.loader ;
navigationContainer.addChild(event.target.loader);
showImage(swfContent);
if ( swfName.name == 'topNavigation' )
{
swfContent.addEventListener("clickHandle",topNavigationClickHandler);
}
}
private function topNavigationClickHandler():void
{
trace('Back to root');
}
private function showImage(navigationItem):void
{
try
{
navigationItem.alpha = 0;
Tweener.addTween(navigationItem, { alpha:1, time:1, transition:"easeOutSine" } );
navigationItem.smoothing = true;
} catch (e:Error) { trace('Error no tweening'); };
stageResize();
}
private function stageResize(e:Event=null):void
{
var centerImages:Array = new Array ( contentContainer, navigationContainer, backgroundImage ) ;
backgroundImage.x = 0;
backgroundImage.y = 0;
backgroundImage.scaleX = backgroundImage.scaleY = 1;
if ((stage.stageHeight / stage.stageWidth) < backgroundImage.height / backgroundImage.width) {
backgroundImage.width = stage.stageWidth;
backgroundImage.scaleY = backgroundImage.scaleX;
} else {
backgroundImage.height = stage.stageHeight;
backgroundImage.scaleX = backgroundImage.scaleY;
}
for each ( var centered:MovieClip in centerImages )
{
centered.x = stage.stageWidth / 2 - centered.width / 2;
centered.y = stage.stageHeight / 2 - centered.height / 2;
}
}
}
}
This is my code for the main.as.
And here my code for my loaded SWF on the maintimeline.
addEventListener(Event.ADDED_TO_STAGE, init);
function init(event:Event):void
{
trace('try dispatch');
dispatchEvent(new Event("clickHandle",true));
}
Try dispatch works, but it does not get back to the main to fire up "Back to root".
Any idea?
thx!
As long as all movieclips dispatching events are added to the display list, this should work. This makes me think that perhaps the event listener being added is not working. Try adding a trace statement to the block of code as shown below:
if ( swfName.name == 'topNavigation' )
{
trace("adding listener");
swfContent.addEventListener("clickHandle",topNavigationClickHandler);
}
I expect that this if condition is failing, and thus your listener is never being created. Also, you need to add a function parameter to the callback method "topNavigationClickHandler" to accept the event as the callback parameter. You have not done this, and this is an error that would be thrown at runtime when the event was received and dispatched to the callback method. You havn't seen this yet because your listener has never had to invoke the callback. So you're gonna have to fix this code like so:
private function topNavigationClickHandler(e:Event):void
{
trace('Back to root');
}
Also I just want to add that your if condition on setting this listener seems a bit redundant, since you already know you are expecting the navigation swf, because you're explicitly loading it. Also I don't believe the name property would be set like this. Typically the name is only set inside the IDE before compilation, and if it isn't, it gets dynamically generated at runtime. What might be more useful is to check the URL of the loaded SWF to see if it contains "topNavigation" or whatever the swf name is. You can do this like so:
var swfUrl:String = myLoader.contentLoaderInfo.url;
if (swfUrl.search("topNavigation") != -1){
//Match found, add listener for navigation
}