Single Loader to multiple Sprite Possible? - actionscript-3

I've looked in various resources regarding this topic, and it seems to me that I need a Loader for every Sprite which contains an image file (png).
I'm trying to make a Tile Rendering System, and have created a grid of X by Y sprites, but all of them actually reference the same image file.
Is there any other way to do this? (Make the sprite share the same png data file)
Some sample code of what I have done.
// Create an array of X * Y Loaders
var cTileLoaders:Array = new Array( 100 ); // for example 10 by 10 grid
var cTiles:Array = new Array( 100 );
var nIndex:int = 0;
var nImgLoadCount:int = 0;
for ( ; 100 > nIndex; ++nIndex ) {
cTileLoaders[ nIndex ] = new Loader();
cTiles[ nIndex ] = new Sprite();
// perform more sprite initialization
....
cTileLoaders[ nIndex ].contentLoaderInfo.addEventListener( Event.COMPLETE, ImageLoaded
cTileLoaders[ nIndex ].Load( new URLRequest( "some image path" ) );
}
// handler for image loaded
function ImageLoaded( eEvent:Event ):void {
++nImgLoadCount;
// when all 100 sprite data are loaded
// assuming there is no i/o error
if ( 100 == nImgLoadCount ) {
cTiles[ nIndex ].addChild( cTileLoaders[ nIndex ].content );
}
}

I think the answer in your case is to utilise the Bitmap data contained within the image you're loading like this:
var tilesWide:uint = 10;
var tilesHigh:uint = 10;
var tileHolder:Sprite = new Sprite();
this.addChild(tileHolder);
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImgLoaded);
loader.load(new URLRequest("tile.png"));
function onImgLoaded(e:Event):void
{
/* Create a template bitmap to hold the image info */
var templateBitmap:Bitmap = e.target.content;
var templateBitmapData:BitmapData = templateBitmap.bitmapData;
/* Loop through your tiles */
for (var a:uint = 0; a < tilesWide; a++)
{
for (var b:uint = 0; b < tilesHigh; b++)
{
var tile:Sprite = new Sprite();
/* Attach the template BitmapData to each tile */
var tileBitmap:Bitmap = new Bitmap(templateBitmapData);
tile.addChild(tileBitmap);
tile.x = a * tile.width;
tile.y = b * tile.height;
tileHolder.addChild(tile);
}
}
}

You could also use SpriteFactory, a little library I wrote specifically for this:
var tilesWide:uint = 10;
var tilesHigh:uint = 10;
var tileHolder:Sprite = new Sprite();
var tilePath:String = "some/image/path.png";
var factory:SpriteFactory = new SpriteFactory();
factory.loadBitmap("tile", tilePath);
for (var a:uint = 0; a < tilesWide; a++)
{
for (var b:uint = 0; b < tilesHigh; b++)
{
var tile:Sprite = factory.newSprite("tile");
tile.x = a * tile.width;
tile.y = b * tile.height;
tileHolder.addChild(tile);
}
}
The advantage here being that you can use the sprites right away, and they'll automatically be filled with the bitmap once it's loaded.

Related

How to place multiple bitmaps in a scrollable rectangle? AS3

This code builds a palette of tiles for use in a map maker program. It takes in an array set by its parent and uses the bitmaps(from the objects) in that array to display a grid of tiles. Right now it only does a 5x5 grid, but what if there are more than 25 tiles in my tileSet? I want to display only the 5x5 tile grid, but be able to scroll through the images. I imagine that I need to make another rectangle to use as its mask and use a ScrollBar to make it scrollRect, but I can't get this working. Please Help.
public function Palette(X:uint, Y:uint, tileSet:Array)
{
addChild(handleGraphics);
var palette:Rectangle = new Rectangle(X, Y, 5*32, tileSet.length*32); //Default size is 5x5 tiles.
handleGraphics.DrawGrid(32,palette.x,palette.y,5,5);
var counter:int = 0;
for(var i:int = 0; i < 5; i++)
{
paletteArray[i] = [];
for(var u:int = 0; u < 5; u++)
{
if(counter >= tileSet.length)
{
counter = 0; //Which frame to show?
}
var b:Bitmap = new Bitmap(tileSet[counter].Graphic);
b.x = (palette.x) + 32 * u; //Align with palette Rectangle.
b.y = (palette.y) + 32 * i; ///////////////////////////////
addChild(b);
var tileObj:Object = new Object();
tileObj.Name = tileSet[counter].Name;
tileObj.Frame = tileSet[counter].Frame;
tileObj.Graphic = tileSet[counter].Graphic;
paletteArray[i].push(tileObj);
setChildIndex(b, 0); //Under grid.
counter++;
}
}
ActivatePaletteListeners();
}
This code works great for a tileSet array that has less than 25 objects. It loops and shows them continuously until it hits 25. I could do without this I guess, but it is a neat affect.
In another class (HandleTiles) I cycle through my tileSet MovieClip and use each frame to create a new object for each tile.
public function GetPaletteTiles(MC:MovieClip)
{
if (tileArray != null)
{
tileArray.length = 0;
}
for(var i:int = 1; i <= MC.totalFrames; i++)
{
MC.gotoAndStop(i); //Change frame for new info.
var tileObj:Object = new Object(); //The object to push to an array of tiles.
var graphicData:BitmapData = new BitmapData(32,32);
graphicData.draw(MC); //Graphic data from sampleTS.
tileObj.Name = MC.currentFrameLabel;
tileObj.Frame = MC.currentFrame;
tileObj.Graphic = graphicData;
tileArray.push(tileObj);
}
BuildIndexArray(15, 20); //Default size 15 x 20.
}
And here I set the tileSet to use
private function ChangeActiveTileset(Mc:MovieClip)
{
activeTileset = Mc;
GetPaletteTiles(activeTileset);
UpdatePalette();
}
I can change the tileSet with a comboBox. That's why I tear down the tileArray every time I call GetPaletteTiles(). Each tileSet is a different MovieClip, like Buildings, Samples, InTheCity, etc.
Sorry I didn't have time to get this code together earlier. Here's tiling code pieces. Because you're using rectangle and you have to stay under max dimensions you have to move the source mc. I think you already know everything else in there.
// set the bmp dimensions to device screensize to prevent exceeding device's max bmp dimensions
if (bStagePortrait) {
iTileWidth = Capabilities.screenResolutionX;
iTileHeight = Capabilities.screenResolutionY;
} else {
iTileWidth = Capabilities.screenResolutionY;
iTileHeight = Capabilities.screenResolutionX;
}
// mcList.mcListVector is the source mc - a regular mc containing mcs, jpgs, dynamic text, vector shapes, etc.
// mcList.mcListBmp is an empty mc
aListTiles = new Array();
iNumberOfTiles = Math.ceil(mcList.height / iTileHeight);
for (i = 0; i < iNumberOfTiles; i++) {
var bmpTile: Bitmap;
// move the source mc
mcList.mcListVector.y = -(i * iTileHeight);
bmpTile = fDrawTile(mcList, 0, 0, iTileWidth, iTileHeight);
mcList.mcListBmp.addChild(bmpTile);
bmpTile.x = 0;
bmpTile.y = (i * iTileHeight);
aListTiles.push(bmpTile);
}
// remove the regular mc
mcList.mcListVector.removeChild(mcList.mcListVector.mcPic);
mcList.mcListVector.mcPic = null;
mcList.removeChild(mcList.mcListVector);
mcList.mcListVector = null;
}
function fDrawTile(pClip: MovieClip, pX: int, pY: int, pWidth: int, pHeight: int): Bitmap {
trace("fDrawTile: " + pX + "," + pY + " " + pWidth + "," + pHeight);
var rectTemp: Rectangle = new Rectangle(pX, pY, pWidth, pHeight);
var bdClip: BitmapData = new BitmapData(pWidth, pHeight, true, 0x00000000);
var bdTemp: BitmapData = new BitmapData(pWidth, pHeight, true, 0x00000000);
bdClip.draw(pClip, null, null, null, rectTemp, true);
bdTemp.copyPixels(bdClip, rectTemp, new Point(0, 0));
var bmpReturn: Bitmap = new Bitmap(bdTemp, "auto", true);
return bmpReturn;
}

actionscript 3.0 visible mask over a visible masked object

I have a moving truck in my game and I want the city lights reflections (NOT the background) to be visible over its body as it moves around.
What stands behind the truck does not matter, some trees and buildings.
So,
I add the background (not important);
then I add the truck to the stage;
then I add another MovieClip with the size of the whole stage (city lights and stuff) and I set it as a masking object for my truck.
I dont want the truck to disappear, i just want the masking object show up over it with some transparency;
I know about masking and also catching my movieclips as bitmaps but it wont work in my case; because here the truck stays totally visible and the mask semi-transparent.
Please help me, I'm running out of time:/
EDIT
Here is my current code based off one of the asnwers:
var buildingHolder: Sprite = new Sprite;
this.addChild(buildingHolder);
var Mask: Sprite = new Sprite()
Mask = Sprite(buildingHolder);
Mask.alpha = 1;
Mask.cacheAsBitmap = true;
this.addChild(Mask);
var reflection: MovieClip = new nightSky1Mask;
reflection.x = 0;
reflection.y = 480;
reflection.alpha = .6;
reflection.scaleX *= 320 / reflection.width;
reflection.scaleY = reflection.scaleX;
reflection.cacheAsBitmap = true;
reflection.mask = Mask;
this.addChild(reflection);
for (var i: int = 0; i <= 29; i++){
//some codes are deleted here
var image: MovieClip = new level1Images[i];
image.x = // deleted
image.y = // deleted
image.scaleX *= 30 / image.width * 2;
image.scaleY *= 5 / image.width * 2;
buildingHolder.addChild(image)
currLevelImages.push(image)
}
You DON'T want to mask the truck. What you want to mask are the city lights.
You need to create a copy of the truck, and mask the city lights with that.
Assuming you have a Bitmap in your library with exported class as TruckImage and your lights are exported for actionscript as Lights, you can do something like this:
var truck:Bitmap = new Bitmap(new TruckImage());
//scale and position however you'd like
truck.scaleX = truck.scaleY = .25;
truck.y = 100;
addChild(truck);
var theMask:Bitmap = new Bitmap(truck.bitmapData);
theMask.cacheAsBitmap = true;//!very important
theMask.scaleX = theMask.scaleY = truck.scaleX;
addChild(theMask); //also important
lights = new Bitmap(new Lights());
lights.cacheAsBitmap = true;//!very important
lights.mask = theMask;
addChild(lights);
//let's move the truck and the mask every frame
addEventListener(Event.ENTER_FRAME,enterFrame);
function enterFrame(e:Event):void {
truck.x = (truck.x + 2) % stage.stageWidth;
theMask.x = truck.x;
}
EDIT
Try something like this: (creating a bitmap copy of your building)
var buildingHolder:Sprite = new Sprite();
this.addChild(buildingHolder);
//create a bitmap data object and draw the building holder sprite into it (making a copy)
var maskBMD:BitmapData = new BitmapData(buildingHolder.width,buildingHolder.height,true,0x00000000);
maskBMD.draw(buildingHolder);
var msk:Bitmap = new Bitmap(maskBMD,"auto",true);
msk.cacheAsBitmap = true;
this.addChild(msk);
var reflection:MovieClip = new nightSky1Mask;
reflection.x = 0;
reflection.y = 480;
reflection.alpha = .6;
reflection.scaleX *= 320 / reflection.width;
reflection.scaleY = reflection.scaleX;
reflection.cacheAsBitmap = true;
reflection.mask = msk;
this.addChild(reflection);
for (var i: int = 0; i <= 29; i++){
//some codes are deleted here
var image: MovieClip = new level1Images[i];
image.x = // deleted
image.y = // deleted
image.scaleX *= 30 / image.width * 2;
image.scaleY *= 5 / image.width * 2;
buildingHolder.addChild(image)
currLevelImages.push(image)
}
Or, you could do something like this to make two copies of your building:
var buildingHolder:Sprite = createBuilding();
var buildingHolderMask:Sprite = createBuilding(false);
function createBuilding(addToArray:Boolean = true):Sprite {
var building:Sprite = new Sprite();
for (var i: int = 0; i <= 29; i++){
//some codes are deleted here
var image: MovieClip = new level1Images[i];
image.x = // deleted
image.y = // deleted
image.scaleX *= 30 / image.width * 2;
image.scaleY *= 5 / image.width * 2;
building.addChild(image)
if(addToArray) currLevelImages.push(image)
}
return building;
}

How to add Looped URLRequest image and add them to 1 viewport?

I am trying to loop (add images from Loader thru URLRequest), And the images are added to contentHolder, and then i place all these images which are inside contentHolder into a viewport. But at the moment I have to put the add images to viewport step inside the loop, so it creates a problem, which is each loop, a viewport is added. So 10 viewport overlaps each other. I tested it in debug mode and when the first image is loaded i can quickly slide it, because the viewport has a scrollpane, then second image is added, and i can slide that one, and third one is added on top etc.
But if i put the add Holder to viewport step outside the loop, it gives me the error Error #2007: Parameter child must be non-null, i dont know what to do. Please help, thanks for your time! I had been trying this for 6 hrs already!
And the error is on the line viewport.addChild(_contentHolder1); which is the last part of the code, if you scroll to the bottom.
for (var j:int = 5; j < somedata.length; j++)
{
if(somedata[j]){
var myLoader:Loader = new Loader();
var image:Bitmap;
var url:URLRequest = new URLRequest("http://www.rentaid.info/rent/"+somedata[j]);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoaded);
myLoader.load(url);
function onImageLoaded(e:Event):void {
image = new Bitmap(e.target.content.bitmapData);
var currentY:int = 10;
var h = image.height;
var k=image.width/image.height;
_contentHolder = new Sprite();
_contentHolder.y = currentY;
currentY += _contentHolder.height + 10;
addChild(_contentHolder);
_contentHolder.addChild(image);
for (var j:int = 5; j <somedata.length; j++)
{
_contentHolder1 = new Sprite();
addChild(_contentHolder1);
_contentHolder1.addChild(_contentHolder);
var viewport:Viewport = new Viewport();
viewport.y = 0;
viewport.addChild(_contentHolder1);
var scroller:TouchScroller = new TouchScroller();
scroller.width = 300;
scroller.height = 265;
scroller.x = 10;
scroller.y = 100;
scroller.viewport = viewport;
addChild(scroller);
}
}}
Edit:
var loadedArray:Array = new Array();
var counter:int=0;
function loadImage():void{
for (var j:int = 5; j < somedata.length; j++)
{
if(somedata[j]){
var loader:Loader = new Loader();
var image:Bitmap;
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoaded);
loader.load(new URLRequest("http://www.rentaid.info/rent/"+somedata[j][counter]));
}
}
}
function onImageLoaded(e:Event):void {
loadedArray.push(e.currentTarget.loader.content as Bitmap);
if(counter == somedata.length-1){
var _contentHolder: Sprite = new Sprite;
addChild(_contentHolder);
for(var i:uint = 5; i < loadedArray.length; i++){
_contentHolder.addChild(loadedArray[i]);
currentY += _contentHolder.height + 10;
}
}
else{
counter++;
loadImage();
}
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);
}
you can use Starling Framework and a loader loop such as:
private var count:uint = 0; //add this in your class
private var imagesVector:Vector.<Image> = new Vector.<Image>(); //add this in your class
private var imagesUrlVector:Vector.<String> = new <String>["url1","url2","url3","etc"]; //add this in your class
private function loadImages():void
{
//create the loader
var loader:Loader = new Loader();
//when texture is loaded
loader.contentLoaderInfo.addEventListener ( Event.COMPLETE, onComplete );
//load the texture
loader.load( new URLRequest (imagesUrlVector[count]));
}
private function onComplete ( e : Event ):void
{
// grab the loaded bitmap
var loadedBitmap:Bitmap = e.currentTarget.loader.content as Bitmap;
// create a texture from the loaded bitmap
var texture:Texture = Texture.fromBitmap ( loadedBitmap );
var card:CustomImage = new CustomImage(texture);
imagesVector.push(card);
trace("load image number" + count);
count++;
if (count < imagesUrlVector.length) {
loadImages();
} else displayImages();
}
private function displayImages():void {
var x:uint = 150;
var i:Number;
for (i = 0; i < cardVector.length; i++ )
{
x += 100;
imagesVector[i].x = x;
addChild(imagesVector[i]);
}
}

Intermittent/staggered loading of an object

I've just recently tried my hand at actionscript 3 and have come across a road block.
How do I go about rendering the cubes (cube1) intermittently, ie. staggered loading. I need the cubes to load a split second from each other.
Below is a snippet of what I have so far:
var rows:int = 5;
var cols:int = 3;
var spacery:int = 100;
var spacerx:int = 120;
var box_count:int = 8;
for(var i:int; i < box_count; i++) {
cube1 = new Cube(ml,100,10,80,1,1,1);
cube1.y = ((i % rows)) * (cube1.x + spacery);
cube1.x = Math.floor(i/rows) * (cube1.x +spacerx);
cube1.z = 0;
bigBox.addChild(cube1);
}
//Create an array out side the function; as a global (instance) variable:
var cubes:Array = [];
//instead of bigBox.addChild(cube1), store them in the array:
cubes.push(cube1);
//initialize a timer outside after for loop
//Fire every 100 milliseconds, box_count times
var timer:Timer = new Timer(100, box_count);
timer.addEventListener(TimerEvent.TIMER, onTick);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, onTickDone);
function onTick(e:Event):void
{
bigBox.addChild(cubes[timer.currentCount]);
}
function onTickDone(e:Event):void
{
cubes = null;
timer.removeEventListener(TimerEvent.TIMER, onTick);
timer.removeEventListener(TimerEvent.TIMER_COMPLETE, onTickDone);
timer = null;
}

AS3 proportionally scaling external image

Currently I am using a for loop to dynamically load XML images and place them in a grid as thumbnails. I have the arrangement set and all the data is loading smoothly, but now I need to make the images scale to small 100px x 100px thumbs in small container movieclips. My code is as follows.
import gs.*;
import gs.easing.*;
var bttnHeight:Number = 20;
var select:Number = 0;
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, showXML);
xmlLoader.load(new URLRequest("testxml.xml"));
var list_mc:Array = new Array();
function showXML(e:Event):void {
XML.ignoreWhitespace = true;
var nodes:XML = new XML(e.target.data);
var gallcount = nodes.gallery.length();
var list_mc = new listitem();
//Generate menu to select gallery
function populateMenu():void {
var spacing:Number = 0;
for (var i=0; i<gallcount; i++) {
list_mc[i] = new listitem();
list_mc[i].name = "li" + i;
list_mc[i].y = i*bttnHeight;
list_mc[i].gallname.text = nodes.gallery[i].attributes();
menu_mc.addChild(list_mc[i]);
list_mc[i].addEventListener(MouseEvent.ROLL_OVER, rollover);
list_mc[i].addEventListener(MouseEvent.ROLL_OUT, rollout);
list_mc[i].buttonMode = true;
list_mc[i].mouseChildren = false;
}
menu_mc.mask = mask_mc;
}
//list_mc.mask(mask_mc);
var boundryWidth = mask_mc.width;
var boundryHeight = mask_mc.height;
var diff:Number = 0;
var destY:Number = 0;
var ratio:Number = 0;
var buffer:Number = bttnHeight*2;
function findDest(e:MouseEvent):void {
if (mouseX>0 && mouseX<(boundryWidth)) {
if (mouseY >0 && mouseY<(boundryHeight)) {
ratio = mouseY/boundryHeight;
diff = menu_mc.height-boundryHeight+buffer;
destY = Math.floor(-ratio*diff)+buffer/2;
}
}
}
var tween:Number = 5;
//This creats the scroll easing
function moveMenu() {
if (menu_mc.height>boundryHeight) {
menu_mc.y += (destY-menu_mc.y)/tween;
if (menu_mc.y>0) {
menu_mc.y = 0;
} else if (menu_mc.y<(boundryHeight-menu_mc.height)) {
menu_mc.y = boundryHeight-menu_mc.height;
}
}
}
function rollover(e:Event):void {
TweenLite.to(e.currentTarget.li_bg, .4, {tint:0x334499});
}
function rollout(e:Event):void {
TweenLite.to(e.currentTarget.li_bg, .4, {removeTint:true});
}
stage.addEventListener(MouseEvent.MOUSE_MOVE, findDest);
stage.addEventListener(Event.ENTER_FRAME, moveMenu);
populateMenu();
select = 0;
//Generate thumbnails
function genThumb():void {
var photos = nodes.gallery[select].photo;
var thumbframe:Array = new Array();
var row = 0;
var column = 0;
var loaderArray:Array = new Array();
for (var i=0; i<photos.length(); i++) {
thumbframe[i] = new Sprite;
thumbframe[i].graphics.beginFill(0x0000FF);
thumbframe[i].graphics.drawRect(0,0,100,100);
thumbframe[i].graphics.endFill();
thumbframe[i].y = row;
thumbframe[i].x = column;
loaderArray[i] = new Loader();
loaderArray[i].load(new URLRequest(photos[i].text()));
trace(loaderArray[i].height);
var index = i+1;
container_mc.addChild(thumbframe[i]);
if (index%5 == 0) {
row=row+120;
column = 0;
} else {
column=column+120;
}
thumbframe[i].addChild(loaderArray[i]);
}
}
genThumb();
}
Both the loaders and the containers are in respective arrays. The images load correctly, but I am at a loss for how to scale them (ultimately I'd like to integrate a tween to animate as they load as well if possible.)
Thanks in advance for any aid!
You look like you need to scale your bitmaps into a 100x100 square. You'll need to wait until the loader has completed loading to do that because until then you won't know what the dimensions of the item are.
When you create your loader, add an event listener, like this:
loaderArray[i].contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
and then add this function:
function onLoadComplete(event:Event):void
{
var info:LoaderInfo = LoaderInfo(event.currentTarget);
info.removeEventListener(Event.COMPLETE);
var loader:Loader = info.loader;
var scaleWidth:Number = 100 / loader.width;
var scaleHeight:Number = 100 / loader.height;
if (scaleWidth < scaleHeight)
loader.scaleX = loader.scaleY = scaleWidth;
else
loader.scaleX = loader.scaleY = scaleHeight;
}
This may be a bit complicated, but all it really does is clean up the event listener that you had added, and find the dimensions of the loader (which it can get now because it's finished loading), and scale the loader appropriately.
If you need it to be centered within your thumbnail, add this to the bottom of the onLoadComplete method:
loader.x = (100 - loader.width) * 0.5;
loader.y = (100 - loader.height) * 0.5;
or you need it to take up the whole thumbnail and cut off the edges, change it to this (the inequality is the other-way around)
if (scaleWidth > scaleHeight)
loader.scaleX = loader.scaleY = scaleWidth;
else
loader.scaleX = loader.scaleY = scaleHeight;
and add this:
var shape:Shape = new Shape();
var g:Graphics = shape.graphics;
g.beginFill(0x00FF00);
g.drawRect(0, 0, 100, 100);
g.endFill();
loader.mask = g;
I haven't tested this, so there may be a few glitches, but hopefully it gives you the right idea.