Waiting for Embedded Image to Load? - actionscript-3

So I'm trying to load a sprite sheet. I've embedded it into the .swf, but when I instantiate a class and call a function that starts clipping from the sprite sheet, I get the error:
"Parameter sourceBitmapData must be non-null."
I know that what is happening is that the code is being called before the sprite sheet image is actually loaded, but I'm not sure how to solve this problem since I'm embedding rather than using a loader. I assume I'll need to use event listeners, but how do I make that work with the embedding? Here's my code so far:
In the Main public class:
private var currentSprite:SpriteSheet;
[Embed(source='../assets/images/sprite_sheet_1.png')]
private var sheetClass:Class;
private var sheet:Bitmap = new sheetClass();
Then in the Main function:
currentSprite = new SpriteSheet( sheet, 25, 25 );
addChild(currentSprite);
The SpriteSheet function is set up like so:
public function SpriteSheet(tileSheetBitmap:Bitmap, width:Number = 25, height:Number = 25) {
tileSheetBitmapData = tileSheetBitmap.bitmapData;
tileWidth = width;
tileHeight = height;
rowLength = int(tileSheetBitmap.width / width );
tileRectangle = new Rectangle( 0, 0, tileWidth, tileHeight );
tilePoint = new Point( 0, 0 );
canvasBitmapData = new BitmapData( tileWidth, tileHeight, true );
var canvasBitmap:Bitmap = new Bitmap(canvasBitmapData);
addChild(canvasBitmap);
drawTile(0);
addEventListener(Event.REMOVED_FROM_STAGE, remove);
}
In my SpriteSheet class, I call a drawTile function which calls copyPixels(), where the error is originating from:
canvasBitmapData.copyPixels(tileSheetBitmapData, tileRectangle, tilePoint);
I know that's a lot of code, but I feel there's probably a simple solution. Any feedback would be greatly appreciated. Thanks!
Edit: Here is the SpriteSheet class:
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.events.Event;
public class SpriteSheet extends Sprite {
public var tileSheetBitmapData:BitmapData;
private var canvasBitmapData:BitmapData;
private var tileWidth:int;
private var tileHeight:int;
private var rowLength:int;
private var tileRectangle:Rectangle;
private var tilePoint:Point;
public function SpriteSheet(tileSheetBitmap:Bitmap, width:Number = 25, height:Number = 25) {
tileSheetBitmapData = tileSheetBitmap.bitmapData;
if(tileSheetBitmap != null ) {
trace("tileSheetBitmap is not null in SpriteSheet");
}
if( tileSheetBitmapData != null ){
trace("tileSheetBitmapData is not null in SpriteSheet");
}
tileWidth = width;
tileHeight = height;
rowLength = int(tileSheetBitmap.width / width );
tileRectangle = new Rectangle( 0, 0, tileWidth, tileHeight );
tilePoint = new Point( 0, 0 );
canvasBitmapData = new BitmapData( tileWidth, tileHeight, true );
var canvasBitmap:Bitmap = new Bitmap(canvasBitmapData);
addChild(canvasBitmap);
drawTile(0);
addEventListener(Event.REMOVED_FROM_STAGE, remove);
} //end of SpriteSheet
public function drawTile(tileNumber:int):BitmapData {
trace("Reached drawTile");
tileRectangle.x = int( (tileNumber % rowLength) ) * tileWidth;
tileRectangle.y = int( (tileNumber / rowLength) ) * tileHeight;
canvasBitmapData.copyPixels(tileSheetBitmapData, tileRectangle, tilePoint);
trace("Reached past copyPixels");
return canvasBitmapData.clone();
} //end of drawTile
public function tileBoard(boardIndex:Array):BitmapData {
var wide:int = boardIndex[0].length;
var tall:int = boardIndex.length;
canvasBitmapData = new BitmapData( (tileWidth * wide), (tileHeight * tall), true);
var boardCanvas:Bitmap = Bitmap(getChildAt(0));
boardCanvas.bitmapData = canvasBitmapData;
tileRectangle = new Rectangle( 0, 0, (tileWidth * wide), (tileHeight * tall) );
for( var i:int = 0; i < wide; i++ ) {
for( var j:int = 0; j < tall; j++ ) {
tilePoint = new Point((tileWidth * i), (tileHeight * j) );
drawTile(boardIndex[j][i]);
}
}
return canvasBitmapData.clone();
} //end tileBoard
public function remove(e:Event):void {
tileSheetBitmapData.dispose();
canvasBitmapData.dispose();
} //end remove
} //end class SpriteSheet
} //end package

This isn't a loading issue, since you're embedding the png file into your swf, all the image loading is done while the swf is loaded.
this is a problem with the Flash IDE compiler only... With Flex compiler this is not necessary...
try:
private var sheet:BitmapData = new sheetClass(0,0);
change your SpriteSheet class to accept the bitmapData directly

Related

Stage dimensions in a new NativeWindow

i'm building a flash desktop App where the user clicks on a button and opens a SWF file (a game) in a new window, i used a NativeWindow to achieve it, i did the folowing:
var windowOptions:NativeWindowInitOptions = new NativeWindowInitOptions();
windowOptions.systemChrome = NativeWindowSystemChrome.STANDARD;
windowOptions.type = NativeWindowType.NORMAL;
var newWindow:NativeWindow = new NativeWindow(windowOptions);
newWindow.stage.scaleMode = StageScaleMode.NO_SCALE;
newWindow.stage.align = StageAlign.TOP_LEFT;
newWindow.bounds = new Rectangle(100, 100, 2000, 800);
newWindow.activate();
var aLoader:Loader = new Loader;
aLoader.load(new URLRequest(path));
newWindow.stage.addChild(aLoader);
the result is this:
the game doesn't take the whole space available. When i change the "NO_SCALE" to "EXACT_FIT":
newWindow.stage.scaleMode = StageScaleMode.EXACT_FIT;
i got this:
it only shows the top-left corner of the game. I also tried "SHOW_ALL" and "NO_BORDER". I got the same result as "EXACT_FIT".
When i open the SWF file of the game separatly it's displayed normally:
any idea how can i display the SWF game as the image above?
The best solution for that is to have the dimensions of your external game in pixel. you have to stretch the loader to fit it in your stage. if you are try to load different games with different sizes to your stage, save the swf dimensions with their URL addresses.
var extSWFW:Number = 550;
var extSWFH:Number = 400;
var extURL:String = "./Data/someSwf.swf";
var mainStageWidth:Number = 1024;
var mainStageHeight:Nubmer = 768;
var aLoader:Loader = new Loader;
aLoader.load(new URLRequest(extURL));
newWindow.stage.addChild(aLoader);
aLoader.scaleY = aLoader.scaleX = Math.min(mainStageWidth/extSWFW,mainStageHeight/extSWFH);
It is not very difficult to figure dimensions of a loaded SWF because it is engraved into it's header, you can read and parse it upon loading. Here's the working sample:
package assortie
{
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Rectangle;
import flash.net.URLRequest;
import flash.utils.ByteArray;
public class Dimensions extends Sprite
{
private var loader:Loader;
public function Dimensions()
{
super();
loader = new Loader;
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
loader.load(new URLRequest("outer.swf"));
}
private function onLoaded(e:Event):void
{
var aBytes:ByteArray = loader.contentLoaderInfo.bytes;
var aRect:Rectangle = new Rectangle;
var aRead:BitReader = new BitReader(aBytes, 8);
var perEntry:uint = aRead.readUnsigned(5);
aRect.left = aRead.readSigned(perEntry) / 20;
aRect.right = aRead.readSigned(perEntry) / 20;
aRect.top = aRead.readSigned(perEntry) / 20;
aRect.bottom = aRead.readSigned(perEntry) / 20;
aRead.dispose();
aRead = null;
trace(aRect);
}
}
}
import flash.utils.ByteArray;
internal class BitReader
{
private var bytes:ByteArray;
private var position:int;
private var bits:String;
public function BitReader(source:ByteArray, start:int)
{
bits = "";
bytes = source;
position = start;
}
public function readSigned(length:int):int
{
var aSign:int = (readBits(1) == "1")? -1: 1;
return aSign * int(readUnsigned(length - 1));
}
public function readUnsigned(length:int):uint
{
return parseInt(readBits(length), 2);
}
private function readBits(length:int):String
{
while (length > bits.length) readAhead();
var result:String = bits.substr(0, length);
bits = bits.substr(length);
return result;
}
static private const Z:String = "00000000";
private function readAhead():void
{
var wasBits:String = bits;
var aByte:String = bytes[position].toString(2);
bits += Z.substr(aByte.length) + aByte;
position++;
}
public function dispose():void
{
bits = null;
bytes = null;
}
}

Duplicating video Stream Actionscript 3

Good Morning,
i am working on a video class, using a CRTMP Server for streaming. This works fine, but for my solution i need to duplicate the video stream (for some effects).
I googled for duplicate MovieClips and tried to duplicate the video like this.
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.media.*;
import flash.system.*;
import flash.utils.ByteArray;
public class Main extends MovieClip
{
public var netStreamObj:NetStream;
public var nc:NetConnection;
public var vid:Video;
public var vid2:Video;
public var streamID:String;
public var videoURL:String;
public var metaListener:Object;
public function Main()
{
init_RTMP();
}
private function init_RTMP():void
{
streamID = "szene3.f4v";
videoURL = "rtmp://213.136.73.230/maya";
vid = new Video(); //typo! was "vid = new video();"
vid2 = new Video();
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
nc.client = {onBWDone: function():void
{
}};
nc.connect(videoURL);
}
private function onConnectionStatus(e:NetStatusEvent):void
{
if (e.info.code == "NetConnection.Connect.Success")
{
trace("Creating NetStream");
netStreamObj = new NetStream(nc);
metaListener = new Object();
metaListener.onMetaData = received_Meta;
netStreamObj.client = metaListener;
netStreamObj.play(streamID);
vid.attachNetStream(netStreamObj);
//vid2.attachNetStream(netStreamObj); // wont work
addChild(vid);
// addChild(vid2); // wont work either
//intervalID = setInterval(playback, 1000);
}
}
private function asyncErrorHandler(event:AsyncErrorEvent):void
{
trace("asyncErrorHandler.." + "\r");
}
private function received_Meta(data:Object):void
{
var _stageW:int = stage.stageWidth;
var _stageH:int = stage.stageHeight;
var _videoW:int;
var _videoH:int;
var _aspectH:int;
var Aspect_num:Number; //should be an "int" but that gives blank picture with sound
Aspect_num = data.width / data.height;
//Aspect ratio calculated here..
_videoW = _stageW;
_videoH = _videoW / Aspect_num;
_aspectH = (_stageH - _videoH) / 2;
vid.x = 0;
vid.y = _aspectH;
vid.width = _videoW;
vid.height = _videoH;
vid2.x = 0;
vid2.y = _aspectH ;
}
}
It should be possible to duplicate the video stream. 2 Instance of the same videoStream. What am i doing wrong ?
Thanks for help.
"This means that i have to double the netstream. This is not what i want."
"I tried to duplicate the video per Bitmap.clone. But i got an sandbox violation."
You can try the workaround suggested here: Netstream Play(null) Bitmapdata Workaround
I'll show a quick demo of how it can be applied to your code.
This demo code assumes your canvas is width=550 & height=400. Keep that ratio if scaling up.
package
{
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.media.*;
import flash.system.*;
import flash.utils.ByteArray;
import flash.geom.*;
import flash.filters.ColorMatrixFilter;
public class Main extends MovieClip
{
public var netStreamObj:NetStream;
public var nc:NetConnection;
public var vid:Video;
public var streamID:String;
public var videoURL:String;
public var metaListener:Object;
public var vid1_sprite : Sprite = new Sprite();
public var vid2_sprite : Sprite = new Sprite();
public var vid2_BMP : Bitmap;
public var vid2_BMD : BitmapData;
public var colMtx:Array = new Array(); //for ColorMatrix effects
public var CMfilter:ColorMatrixFilter;
public function Main()
{
init_RTMP();
}
private function init_RTMP():void
{
streamID = "szene3.f4v";
videoURL = "rtmp://213.136.73.230/maya";
vid = new Video();
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
nc.client = { onBWDone: function():void { } };
//nc.connect(null); //for file playback
nc.connect(videoURL); //for RTMP streams
}
private function onConnectionStatus(e:NetStatusEvent):void
{
if (e.info.code == "NetConnection.Connect.Success")
{
trace("Creating NetStream");
netStreamObj = new NetStream(nc);
metaListener = new Object();
metaListener.onMetaData = received_Meta;
netStreamObj.client = metaListener;
//netStreamObj.play("vid.flv"); //if File
netStreamObj.play(streamID); //if RTMP
vid.attachNetStream(netStreamObj);
}
}
private function asyncErrorHandler(event:AsyncErrorEvent):void
{
trace("asyncErrorHandler.." + "\r");
}
private function received_Meta(data:Object):void
{
trace("Getting metadata");
var _stageW:int = stage.stageWidth;
var _stageH:int = stage.stageHeight;
var _videoW:int = data.width;
var _videoH:int = data.height;
var _aspectH:int = 0;
var Aspect_num:Number;
Aspect_num = data.width / data.height;
//Aspect ratio calculated here..
_videoW = _stageW;
_videoH = _videoW / Aspect_num;
_aspectH = (_stageH - _videoH) / 2;
trace("_videoW : " + _videoW);
trace("_videoW : " + _videoH);
trace("_aspectH : " + _aspectH);
vid.x = 0;
vid.y = 0;
vid.width = _videoW;
vid.height = _videoH;
setup_Copy(); //# Do this after video resize
}
public function setup_Copy () : void
{
vid2_BMD = new BitmapData(vid.width, vid.height, false, 0);
vid2_BMP = new Bitmap( vid2_BMD );
vid1_sprite.addChild(vid);
vid1_sprite.x = 0;
vid1_sprite.y = 0;
addChild( vid1_sprite );
vid2_sprite.addChild( vid2_BMP );
vid2_sprite.x = 0;
vid2_sprite.y = vid.height + 5;
addChild( vid2_sprite );
stage.addEventListener(Event.ENTER_FRAME, draw_Video);
}
public function draw_Video (evt:Event) : void
{
if ( netStreamObj.client.decodedFrames == netStreamObj.decodedFrames ) { return; } // Here we skip multiple readings
//# Get bitmapdata directly from container of video
if ( vid1_sprite.graphics.readGraphicsData().length > 0 )
{
vid2_BMD = GraphicsBitmapFill(vid1_sprite.graphics.readGraphicsData()[0]).bitmapData;
}
effect_BitmapData(); //# Do an effect to bitmapdata
}
public function effect_BitmapData ( ) : void
{
//# Matrix for Black & White effect
colMtx = colMtx.concat([1/3, 1/3, 1/3, 0, 0]); // red
colMtx = colMtx.concat([1/3, 1/3, 1/3, 0, 0]); // green
colMtx = colMtx.concat([1/3, 1/3, 1/3, 0, 0]); // blue
colMtx = colMtx.concat([0, 0, 0, 1, 0]); // alpha
CMfilter = new ColorMatrixFilter(colMtx);
vid2_BMP.bitmapData.applyFilter(vid2_BMD, new Rectangle(0, 0, vid.width, vid.height), new Point(0, 0), CMfilter);
}
}
}

Simplebutton image is larger than it actually is

I'm creating a button I use beginBitmapFill method to add image to it. Everything works normally, the problem is that the image loaded by a Loader () is greater than it actually is
Class that creates the button
package mode {
import flash.display.Sprite;
import org.osmf.net.StreamingURLResource;
public class LoadButton extends Sprite
{
public var Save;
public function LoadButton(x:uint,save:String,url:String)
{
var button:CustomSimpleButton = new CustomSimpleButton(url);
button.x = x;
Save = save;
addChild(button);
}
}
}
import flash.display.*;
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Shape;
import flash.display.SimpleButton;
import flash.events.*;
import flash.events.EventDispatcher;
import flash.events.MouseEvent;
import flash.net.URLRequest;
import flash.geom.Matrix;
class CustomSimpleButton extends SimpleButton
{
private var upColor:uint = 0xFFCC00;
private var overColor:uint = 0xCCFF00;
private var downColor:uint = 0x00CCFF;
private var sizew:uint = 100;
private var sizeh:uint = 88;
public function CustomSimpleButton(url:String)
{
downState = new ButtonDisplayState(downColor, sizew,sizeh,url);
overState = new ButtonDisplayState(overColor, sizew,sizeh,url);
upState = new ButtonDisplayState(upColor, sizew,sizeh,url);
hitTestState = new ButtonDisplayState(upColor, sizew * 2,sizeh,url);
hitTestState.x = -(sizew / 4);
hitTestState.y = hitTestState.x;
useHandCursor = true;
}
}
class ButtonDisplayState extends Shape
{
private var bgColor:uint;
private var size:uint;
private var sizeh:uint;
public function ButtonDisplayState(bgColor:uint, sizew:uint,sizeh:uint,url:String)
{
this.bgColor = bgColor;
this.size = sizew;
this.sizeh = sizeh;
draw(url);
}
private function draw(url:String):void
{
var myLoader:Loader = new Loader();
var image:Bitmap;
var uri = new URLRequest(url);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event)
{
image = new Bitmap(e.target.content.bitmapData);
graphics.beginBitmapFill(image.bitmapData);
graphics.drawRect(0, 0, 100, 88);
graphics.endFill();
});
myLoader.load(uri);
}
}
How the image is 100x88
as it is
The reason it is showing up cropped like that, is because the BitmapData is larger than the area you are filling.
Before filling the shape with the loaded BitmapData, you need to sale it down to the appropriate size.
Based on the answer to this question, you could do the following:
var scaleAmount:Number;
if(e.target.content.width >= e.target.content.height){
scaleAmount = size / e.target.content.width;
}else{
scaleAmount = sizeh / e.target.content.height;
}
var scaledBitmapData:BitmapData = scaleBitmapData(e.target.content.bitmapData, scaleAmount);
graphics.beginBitmapFill(scaledBitmapData);
graphics.drawRect(0, 0, size, sizeh);
graphics.endFill();
function scaleBitmapData(bitmapData:BitmapData, scale:Number):BitmapData {
scale = Math.abs(scale);
var width:int = (bitmapData.width * scale) || 1;
var height:int = (bitmapData.height * scale) || 1;
var transparent:Boolean = bitmapData.transparent;
var result:BitmapData = new BitmapData(width, height, transparent);
var matrix:Matrix = new Matrix();
matrix.scale(scale, scale);
result.draw(bitmapData, matrix);
return result;
}
It might be easier though, to just make your button state a Sprite and add the loaded Bitmap object and scale it directly:
class ButtonDisplayState extends Sprite
{
private var bgColor:uint;
private var image:Bitmap;
private var size:uint;
private var sizeh:uint;
public function ButtonDisplayState(bgColor:uint, sizew:uint,sizeh:uint,url:String)
{
this.bgColor = bgColor;
this.size = sizew;
this.sizeh = sizeh;
loadImage(url);
}
private function loadImage(url:String):void
{
var myLoader:Loader = new Loader();
var uri = new URLRequest(url);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event)
{
image = new Bitmap(e.target.content.bitmapData);
//scale the bitmap while retaining aspect ratio
//scale based off which dimension (width or height) is bigger
if(image.width >= image.height){
image.scaleX= size / image.width; //scale it to the width specified
image.scaleY = image.scaleX; //make the height aspect ratio match the widths
}else{
image.scaleY = sizeh /image.height;
image.scaleX = image.scaleY;
}
addChild(image); //add it to the display list of this object
});
myLoader.load(uri);
}
}

Correct usage of addtoStage when loading external swf

I am loading an external swf file into a parent swf file.
Previously, I was getting error 1009 and fixed that by using a listener event to add the swf to the stage before running any scripts.
The swf however fails to load completely when embedded into a parent swf as seen in this URL
http://viewer.zmags.com/publication/06b68a69?viewType=pubPreview#/06b68a69/1
Here is the code I am using.
Thank you for any input.
package
{
import com.greensock.TweenLite;
import flash.display.DisplayObject;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.SpreadMethod;
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
public class slider5 extends Sprite
{
public var thumbPath:String = "Trailchair_thumb";
public var featPath:String = "Trailchair";
public var sliderIndex:Number = 1;
public var currBg:Bitmap = new Bitmap();
public var thumbCount:Number = 8;
public var thumbHolder:Sprite = new Sprite();
public var thumbMask:Sprite = new Sprite();
public var thumbX:Number = 0;
public var thmPadding:Number = 10;
public var thmWidth:Number;
public var navLeft:Sprite = new Sprite();
public var navRight:Sprite = new Sprite();
public var timer:Timer = new Timer(5000,0);
public var sliderDir:String = "fwd";
public function slider5()
{
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
public function onAddedToStage(e:Event):void{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
//THE BACKGROUND IMAGE
currBg.alpha = 1;
stage.addChildAt(currBg, 0);
changeBg(sliderIndex);
//The thumbMask a sprite with graphic rectangle
thumbMask.x = 87;
thumbMask.y = 572;
thumbMask.graphics.beginFill(0xFFFFFF);
thumbMask.graphics.drawRect(0,0, 406, 181);
stage.addChildAt(thumbMask, 2);
//The thumbSlider
thumbHolder.x = 228;
thumbHolder.y = 573;
stage.addChildAt(thumbHolder, 1);
thumbHolder.mask = thumbMask;
buildThumbs();
//add the nav
navLeft.x = 100;
navLeft.y = 609;
navRight.x = 496;
navRight.y = 609;
stage.addChildAt(navLeft, 4);
stage.addChildAt(navRight, 4);
var navBmp:Bitmap = new Bitmap();
navBmp.bitmapData = new navarrow(109,109);
var navBmp_Rt:Bitmap = new Bitmap();
navBmp_Rt.bitmapData = new navarrow(109,109);
navLeft.addChild(navBmp);
navLeft.scaleX *= -1;
navRight.addChild(navBmp_Rt);
navLeft.useHandCursor = true;
navLeft.buttonMode = true;
navRight.useHandCursor = true;
navRight.buttonMode = true;
navLeft.name = "left";
navRight.name = "right";
navLeft.addEventListener(MouseEvent.CLICK, navClick);
navRight.addEventListener(MouseEvent.CLICK, navClick);
//add the active item frame
var frame:Sprite = new Sprite();
frame.x = 226;
frame.y = 570;
frame.graphics.lineStyle(10, 0x000000);
frame.graphics.drawRect(0,0,131, 181);
stage.addChildAt(frame, 6);
timer.addEventListener(TimerEvent.TIMER, timeEvt);
timer.start();
}
public function changeBg(index):void
{
//set the first slide from our library and add to the stage
var currBg_Class:Class = getDefinitionByName( featPath + index ) as Class;
currBg.bitmapData = new currBg_Class(597,842);
//fade it in
TweenLite.from(currBg, 0.5, {alpha:0});
}
public function buildThumbs():void
{
var currThm:Class;
for (var i:uint = 1; i<=thumbCount; i++)
{
currThm = getDefinitionByName( thumbPath + i ) as Class;
var thmBmp:Bitmap = new Bitmap();
thmBmp.bitmapData = new currThm(126,176);
thmBmp.x = thumbX;
thumbHolder.addChild(thmBmp);
thumbX += thmBmp.width + thmPadding;
}
thmWidth = thmBmp.width + thmPadding;
}
public function navClick(e):void
{
timer.reset();
timer.start();
var dir:String = e.currentTarget.name;
if (dir=="left" && thumbHolder.x < 228 )
{
sliderIndex--;
TweenLite.to(thumbHolder, 0.5, {x:thumbHolder.x + thmWidth});
//thumbHolder.x = thumbHolder.x + thmWidth;
}
else if (dir=="right" && thumbHolder.x > - 724 )
{
sliderIndex++;
TweenLite.to(thumbHolder, 0.5, {x:thumbHolder.x - thmWidth});
//thumbHolder.x = thumbHolder.x - thmWidth;
}
if (sliderIndex == thumbCount)
{
sliderDir = "bk";
}
if (sliderIndex == 1)
{
sliderDir = "fwd";
}
changeBg(sliderIndex);
}
public function timeEvt(e):void
{
if (sliderDir == "fwd")
{
navRight.dispatchEvent(new Event(MouseEvent.CLICK));
}
else if (sliderDir == "bk")
{
navLeft.dispatchEvent(new Event(MouseEvent.CLICK));
}
}
}
}
If you still need it you can try these two suggestions. Note I didnt know about Zmags and initially assumed that it was your own domain name. That's why I suggested you use the Loader class. It worked for me when I did a test version of a parent.swf' that loaded a test 'child.swf' containing your code. It actually loaded the child swf without problems.
Change from extending Sprite to extending MovieClip
Avoid checking for added to stage in this project
Explanations:
Extending MovieClip instead of Sprite
I Long story short Flash wont like your swf extending Sprite then being opened by a parent loader that extends Movieclip. The ZMag player will be extending MovieClip. It's logical and the docs do confirm this in a way. Whether it fixes your issue or not just keep it MovieClip when using ZMags.
Avoiding Stage referencing in your code..
Looking at this Zmags Q&A documentaion:
http://community.zmags.com/articles/Knowledgebase/Common-questions-on-flash-integration
Looking at Question 4.. In their answer these two stand out.
Reference of the stage parameter in the uploaded SWF conflicting with the publication
Badly or locally referenced resources in the SWF you uploaded which cannot be found
Is it really necessary to have an added_to_stage check in this? If it wont hurt then I suggest dropping the stage_added checking from function slider5() and instead cut/paste in there the code you have from the function onAddedToStage(e:Event).
Hope it helps.

Creating 10 circles in ActionScript 3

Iam trying to create a simple method in AS3 that adds 10 circles, each 30px in diameter in a column down the left-hand-side of the stage, so the first appears in the top-left corner and the last in the bottom-right. I would appreciate any help here. Thanks.
My current code follows: - It currently just returns 10 circles with no positioning.
package
{
import flash.display.*;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class Circles extends MovieClip
{
private var timer:Timer = new Timer(100, 10);
public function Circles()
{
timer.addEventListener(TimerEvent.TIMER, createCircles);
timer.start();
}
private function createCircles(e:TimerEvent):void
{
var bcircle:MovieClip = new MovieClip();
var xpos:int = 0;
var ypos:int = 0;
bcircle.graphics.beginFill(0x0033CC);
bcircle.graphics.drawCircle(xpos,ypos,15);
bcircle.graphics.endFill();
bcircle.x = Math.random() * stage.stageWidth;
bcircle.y = Math.random() * stage.stageHeight;
addChild(bcircle);
}
}
}
bcircle.x = Math.random() * stage.stageWidth;
bcircle.y = Math.random() * stage.stageHeight;
These are the lines you want to be paying attention to as these lines control where each circle is placed when added to the stage.
Circle diameter = 30px, stage height (for example) = 400px.
30 goes into 400 13.33 times (400/30) so each circle needs to be spaced 13.3px further down than the last.
You can store a variable that counts how many circles are already on the stage and use it to multiply 13.3 to find the appropriate y value:
var i:int = 0;
private function createCircles(e:TimerEvent):void
{
var bcircle:MovieClip = new MovieClip();
var xpos:int = 0;
var ypos:int = 0;
bcircle.graphics.beginFill(0x0033CC);
bcircle.graphics.drawCircle(xpos,ypos,15);
bcircle.graphics.endFill();
bcircle.x = 0;
bcircle.y = (30 + 13.3) * i; // First circle placed at 0, Second placed at 43.3...
i++; // Increment i each time function is called
addChild(bcircle);
}
You can apply a similar method to then increment the x position of each circle once i reaches 10 (10 circles have been placed), use a trigger to detect this: if(i == 10)
This might help ...
package {
import flash.display.Graphics;
import flash.display.Sprite;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Circles extends Sprite {
private const _circles:Array = []; // reusable container
private var _timer:Timer;
public function Circles() {
_timer = new Timer(1000, 10);
_timer.addEventListener(TimerEvent.TIMER, timer_timerHandler);
_timer.addEventListener(TimerEvent.TIMER_COMPLETE, timer_timerCompleteHandler);
_timer.start();
}
private function createCircle():Sprite {
const sprite:Sprite = new Sprite();
drawCircleInGraphics(sprite.graphics);
addChild(sprite);
return sprite;
}
private function drawCircleInGraphics(graphics:Graphics, color:uint = 0x0033CC, radius:uint = 15):void {
graphics.beginFill(color);
graphics.drawCircle(0, 0, radius);
graphics.endFill();
}
private function createNewCircleAndPositionIt():void {
_circles[_circles.length] = createCircle();
if (_circles.length > 1) {
const last:Sprite = _circles[_circles.length - 1],
predecessor:Sprite = _circles[_circles.length - 2];
last.x = predecessor.x + 30;
last.y = predecessor.y + 30;
}
}
private function timer_timerHandler(event:TimerEvent):void {
createNewCircleAndPositionIt();
}
private function timer_timerCompleteHandler(event:TimerEvent):void {
_timer.removeEventListener(TimerEvent.TIMER, timer_timerHandler);
_timer.removeEventListener(TimerEvent.TIMER_COMPLETE, timer_timerCompleteHandler);
_timer = null;
}
}
}