I'm creating a banner ad in flash which shows 3 random images from a XML file once the pages loads. My problem is that it will occasionally repeat. I've included my code, any advice?
var pHeight:Number = 84;
var pWidth:Number = 120;
var listLoader:URLLoader = new URLLoader( new URLRequest("www.example.com/example.xml") );
var picLoader:Loader = new Loader();
listLoader.addEventListener(Event.COMPLETE, gotList);
function gotList(evt:Event):void {
var xmlData:XML = XML(listLoader.data);
var numImages:Number = xmlData.picture.length();
var stImage:String = xmlData.picture[Math.floor(numImages*Math.random())].toString();
picLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, gotPic);
picLoader.load( new URLRequest(stImage) );
listLoader.removeEventListener(Event.COMPLETE, gotList);
}
function gotPic(evt:Event):void {
var thisBmp:Bitmap = Bitmap(evt.target.content);
thisBmp.x = 0;
thisBmp.y = 0;
var thisWidth:Number = thisBmp.width;
var thisHeight:Number = thisBmp.height;
thisBmp.scaleX = pWidth/thisWidth;
thisBmp.scaleY = pHeight/thisHeight;
addChild(thisBmp);
picLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, gotPic);
}
As mentioned in the comments, you'll want to move the loading of the XML out of the MovieClip
into your main/document class (or if you're working on the timeline, you can put it there... I'm not condoning that behavior, I just want to be able to answer your question regardless of you method).
Once you've loaded the XML a single time, you can grab the images from there, put them into an Array
, and do a random sort on it:
var images:Array = [];
for each(var imgObj:XML in xml.img){
images.push(imgObj.toString());
}
images.sort(function(a:Object,b:Object):int{return Math.random() > .5 ? -1 : 1})
You will probably need to modify the code above to accommodate the format of your XML.
The next thing you'll want to do is create a public method on your MovieClip
that will allow you to set the image for that clip:
function setPic(stImage:String):void {
picLoader = new Loader();
picLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, gotPic);
picLoader.load( new URLRequest(stImage) );
addChild(picLoader);
}
Finally, you can use this setPic
method to set the image on each instance of your MovieCilp
:
for(var i:int = 0; i < images.length; i++)
{
this["mc"+(i+1)].setPic(images[i]);
}
This is assuming a certain naming convention of your MovieClip
instances (mc1
,mc2
,etc)