LoaderMax image resize - actionscript-3

I am trying to load xml images using LoaderMax and resize them using LiquidArea. When I try to load in a different image with resize using next or thumbnails, I get a weird error I can't understand. I was not able to get help so I've come here. The error message and code can be seen below.
RangeError: Error #2006: The supplied index is out of bounds.
at flash.display::DisplayObjectContainer/addChildAt()
at com.greensock.layout::AutoFitArea/set preview()
at com.greensock.layout.core::LiquidData/refreshLevel()
at com.greensock.layout::LiquidStage/refreshLevels()
at com.greensock.layout.core::LiquidData$/addCacheData()
at com.greensock.layout::LiquidArea/pinCorners()
at com.greensock.layout::LiquidArea/autoPinCorners()
at com.greensock.layout::LiquidArea()
at Main/loadImage()
at Function/<anonymous>()
at Function/http://adobe.com/AS3/2006/builtin::apply()
at com.greensock.core::TweenCore/complete()
at com.greensock::TweenMax/complete()
at com.greensock::TweenMax/renderTime()
at com.greensock.core::SimpleTimeline/renderTime()
at com.greensock::TweenLite$/updateAll()
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.DisplayObject;
import com.greensock.TweenMax;
import com.greensock.layout.*;
import com.greensock.events.LoaderEvent;
import com.greensock.loading.XMLLoader;
import com.greensock.loading.LoaderMax;
import com.greensock.loading.ImageLoader;
import com.greensock.loading.data.ImageLoaderVars;
import com.greensock.loading.display.ContentDisplay;
public class Main extends MovieClip
{
private static const THUMB_WIDTH:Number = 100;
private static const THUMB_HEIGHT:Number = 64;
private static const IMAGE_WIDTH:Number = 550;
private static const IMAGE_HEIGHT:Number = 355;
private var ls:LiquidStage;
private var la:LiquidArea;
private var xImgList:XMLList;
public var arrowRight:MovieClip;
public var arrowLeft:MovieClip;
private var currentImage:String;
private var image:ImageLoader;
private var index:Number = 0;
public function Main()
{
// load in xml
var xPhotography:XMLLoader = new XMLLoader("assets/data.xml");
xPhotography.addEventListener( LoaderEvent.COMPLETE, xmlLoaded );
xPhotography.load();
arrowRight.alpha = arrowLeft.alpha = 0;
arrowRight.addEventListener(MouseEvent.ROLL_OVER, rollOverArrowHandler, false, 0, true);
arrowRight.addEventListener(MouseEvent.ROLL_OUT, rollOutArrowHandler, false, 0, true);
arrowRight.addEventListener( MouseEvent.CLICK, onArrowClick );
arrowLeft.addEventListener(MouseEvent.ROLL_OVER, rollOverArrowHandler, false, 0, true);
arrowLeft.addEventListener(MouseEvent.ROLL_OUT, rollOutArrowHandler, false, 0, true);
arrowLeft.addEventListener( MouseEvent.CLICK, onArrowClick );
}
private function xmlLoaded( e:LoaderEvent ):void
{
var xData:XML = e.target.content;// get copy of xml
xImgList = new XMLList(xData.image);// grabbing xml image nodes
loadImage( 0 );
}
// load in the image
private function loadImage( index: Number ):void
{
ls = new LiquidStage(this.stage,550,419);
la = new LiquidArea(imgContainer, 0, 0, 550, 419);
var file:String = xImgList[index]. # url;
var image:ImageLoader = new ImageLoader("assets/images/" + file, new ImageLoaderVars()
.container( imgContainer )
.x(0)
.y(0)
.alpha( 0 )
.width( IMAGE_WIDTH )
.height( IMAGE_HEIGHT )
.onComplete(completeHandler)
.scaleMode( "proportionalOutside" )
);
image.load();
la.attach(image.content, {scaleMode:ScaleMode.PROPORTIONAL_OUTSIDE, crop:true});
}
private function completeHandler(event:LoaderEvent):void
{
TweenMax.to(event.target.content, 1.5, {alpha:1});
}
private function rollOverArrowHandler(e:MouseEvent):void
{
TweenMax.to(e.currentTarget, 0.5, {alpha:1});
}
private function rollOutArrowHandler(e:MouseEvent):void
{
TweenMax.to(e.currentTarget, 0.5, {alpha:0});
}
private function onArrowClick( e:MouseEvent ):void
{
switch (e.target)
{
case arrowRight :
index++;
break;
case arrowLeft :
index--;
break;
}
if (index == xImgList.length())
{
index = 0;
} else if (index < 0)
{
index = xImgList.length() - 1;
}
checkOldImage( index );// needed to help loading times
}
private function checkOldImage( index:Number ):void
{
var oldClip:DisplayObject = imgContainer.getChildAt( 0 );
var nextIndex = index;
TweenMax.to( oldClip, .5, { autoAlpha: 0, onComplete: completeFadeHandler, onCompleteParams:[oldClip] } );
function completeFadeHandler(child:DisplayObject):void {
if (child.parent) {
child.parent.removeChild(child);
}
loadImage(nextIndex);
}
}
}
}

Related

ActionScript3, dropping on stage not working after using MouseEnabled

I'm trying to do do a BattleShip Flash game using ActionScript 3.
1- I draw a grid (class: com.Battleship.grid) using a gridCell:movieClip (class: com.battleship.GridCell)
2- I draw a ship (class: com.battleship.Bateau)
My objective is when I drag the ship to the grid the alpha cell under the mouse changes, and if I drop:
1- if the droptarget is a gridCell, the ship takes place (works fine)
2- if the droptarget is stage, the ship return to originPosition (not working)
My problem: after I used MouseEnabled= false, the ship can drop on the grid, but not on the stage and still dragging.
Here is my code:
var grid:Grid = new Grid(10,new Point(20,20));
var b1:Bateau = new Bateau();
b1.x = 490;
b1.y = 300;
b1.originPos = new Point(b1.x,b1.y);
addChild(b1)
addChild(grid);
package com.battleship {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.events.Event;
public class Bateau extends MovieClip {
private var _originPos:Point;
public function Bateau() {
originPos = new Point();
buttonMode = true;
addEventListener(MouseEvent.MOUSE_DOWN, onDrag);
}
protected function onDrag(e:MouseEvent):void
{
e.currentTarget.parent.addChild(e.currentTarget);
e.currentTarget.startDrag();
e.currentTarget.mouseEnabled = false;
//e.currentTarget.mouseChildren = false;
addEventListener(MouseEvent.MOUSE_UP, onDrop);
parent.addEventListener(MouseEvent.MOUSE_UP, onDrop);
}
protected function onDrop(e:MouseEvent):void
{
e.currentTarget.mouseEnabled = true;
e.currentTarget.mouseChildren = true;
e.currentTarget.stopDrag();
if(dropTarget == null){
x = originPos.x;
y = originPos.y;
}else{
trace(e.currentTarget.name);
if(dropTarget.parent is GridCell)
{
x = dropTarget.parent.x+20;
y = dropTarget.parent.y;
}
}
}
public function get originPos():Point
{
return _originPos;
}
public function set originPos(originPos:Point):void
{
_originPos = originPos;
}
}
}
package com.battleship {
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class GridCell extends MovieClip {
private var _row:int;
private var _col:int;
private var _val:int;
public function GridCell()
{
addEventListener(MouseEvent.CLICK,onClick);
addEventListener(MouseEvent.MOUSE_OVER,onMouseOver);
addEventListener(MouseEvent.MOUSE_OUT,onMouseOut);
}
public function onClick(e:MouseEvent)
{
//trace("(" + e.currentTarget.row+ ", " + e.currentTarget.col + ")");
trace(e.currentTarget.name);
}
public function onMouseOver(e:MouseEvent)
{
alpha = 0.6;
}
public function onMouseOut(e:MouseEvent)
{
alpha = 1;
}
public function get row():int
{
return _row;
}
public function set row(row:int):void
{
_row = row;
}
public function get col():int
{
return _col;
}
public function set col(col:int):void
{
_col = col;
}
public function get val():int
{
return _val;
}
public function set val(val:int):void
{
_val = val;
}
}
}
package com.battleship {
import flash.geom.Point;
import flash.display.Sprite;
import flash.events.MouseEvent;
public class Grid extends Sprite {
private var _size:int;
private var _position:Point;
public function Grid(size:int,position:Point):void
{
_size = size;
_position = position;
var gridCells:Array = new Array(size,size);
var i,j:int;
for(i=0;i<size;i++)
{
gridCells[i] = new Array();
for(j=0;j<size;j++)
{
var cell:GridCell = new GridCell();
cell.row = j+1;
cell.col = i+1;
cell.x = this.position.x + cell.width * (i+1);
cell.y = this.position.x + cell.height * (j+1);
cell.name = "cell" + (j+1) + (i+1);
//cell.addEventListener(MouseEvent.CLICK,onClick);
gridCells[i][j] = cell;
this.addChild(gridCells[i][j]);
}
}
}
public function get size():int
{
return _size;
}
public function set size(size:int):void
{
_size = size;
}
public function get position():Point
{
return _position;
}
public function set position(position:Point):void
{
_position = position;
}
}
}

How to seamlessly loop Video in Adobe Flash?

I import the video to the stage (name it flvControl), set autoPlay to true and then I am trying the following code that is supposed to do the job, but it doesn't work.
function completeHandler(event:fl.video.VideoEvent):void
{
flvControl.play();
}
flvControl.addEventListener(fl.video.VideoEvent.COMPLETE, completeHandler);
When you test movie in Flash, it has half a second white screen flicker in between playbacks, but when you test in a browser (mine is Chrome) not only there is a flicker in between, on subsequent playthroughs video seems to freeze for about 1-2 seconds and then starts to play from about 1-2 seconds down the video. Which essentially makes looping completely unplayable.
Does anyone know how to make video loop seamlessly in Flash? (And to look seamless in browser too?)
The only way I've found to seamlessly loop video is to load the entire clip into memory ByteArray and then use the appendBytes function of a NetStream connected to a Video instance.
Here is a very basic helper class
package
{
import flash.events.AsyncErrorEvent;
import flash.events.NetStatusEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.NetStreamAppendBytesAction;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.utils.setTimeout;
/**
* #author Michael Archbold (ma#distriqt.com)
*/
public class AppendByteVideoLoop
{
public function AppendByteVideoLoop(video:Video, data:ByteArray):void
{
_video = video;
connect(data);
}
private var _video:Video;
private var _connection:NetConnection;
private var _stream:NetStream;
private var _byteArray:ByteArray;
private var _timer:Timer;
private var _paused : Boolean = false;
public function get paused():Boolean { return _paused; }
public function play():void
{
if (_stream)
_stream.resume();
}
public function pause():void
{
if (_stream)
_stream.pause();
}
public function togglePause():void
{
if (_stream)
_stream.togglePause();
}
private function connect(byteArray:ByteArray):void
{
_byteArray = byteArray;
_connection = new NetConnection();
_connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
_connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
_connection.connect(null);
}
private function addToStream():void
{
_stream.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
_stream.appendBytes(_byteArray);
}
public function onMetaData(metaData:Object):void
{
// _video.width = metaData.width;
// _video.height = metaData.height;
}
public function onXMPData(xmp:Object):void
{
}
public function onPlayStatus(status:Object):void
{
}
private function connectStream():void
{
_stream = new NetStream(_connection);
_stream.client = this;
_stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
_stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
_video.attachNetStream(_stream);
_stream.play(null);
_stream.appendBytes(_byteArray);
_stream.pause();
}
private function netStatusHandler(event:NetStatusEvent):void
{
trace(event.info.code);
switch (event.info.code)
{
case "NetConnection.Connect.Success":
connectStream();
break;
case "NetStream.Play.StreamNotFound":
trace( "Unable to locate video " );
break;
case "NetStream.Pause.Notify":
_paused = true;
break;
case "NetStream.Unpause.Notify":
_paused = false;
break;
case "NetStream.Buffer.Empty":
addToStream();
break;
case "NetStream.Buffer.Full":
break;
}
}
private function securityErrorHandler(event:SecurityErrorEvent):void
{
trace( "securityErrorHandler: " + event.text );
}
private function asyncErrorHandler(event:AsyncErrorEvent):void
{
trace( "asyncErrorHandler: " + event.error.message );
}
}
}
And then use it something like this:
var video:Video = new Video();
video.smoothing = false;
if (stage)
{
video.width = stage.stageWidth;
video.height = stage.stageHeight;
}
addChild( video );
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener( Event.COMPLETE, loader_completeHandler, false, 0, true );
loader.addEventListener( IOErrorEvent.IO_ERROR, loader_ioErrorHandler, false, 0, true );
loader.load( new URLRequest( "URL_OF_VIDEO" ) );
...
function loader_completeHandler( event:Event ):void
{
var data:ByteArray = ByteArray( loader.data );
var player:AppendByteVideoLoop = new AppendByteVideoLoop( _video, _data );
player.play();
}
Hope that helps.

Record Sound Using AS3 Worker

Hello I am trying to record the user sound using AS3 Worker everything works well when it comes to communication between the worker and the main scene but I think the record functionnality have and issue here I am using the Record Clash from bytearray.org (http://www.bytearray.org/?p=1858)
and here's is my code am I missing something :
package objects
{
import flash.events.Event;
import flash.system.MessageChannel;
import flash.system.Worker;
import flash.system.WorkerDomain;
import flash.utils.ByteArray;
import starling.display.Button;
import starling.display.Image;
import starling.display.Sprite;
import starling.events.Event;
public class RecordComponent extends Sprite
{
private var audioContainer:Image;
private var recButton:Button;
private var playButton:Button;
private var stopButton:Button;
//background thread for recording
private var worker:Worker;
private var wtm:MessageChannel;
private var mtw:MessageChannel;
private var output:ByteArray;
public function RecordComponent()
{
super();
worker = WorkerDomain.current.createWorker(Workers.RecordWorker);
wtm = worker.createMessageChannel(Worker.current);
mtw = Worker.current.createMessageChannel(worker);
worker.setSharedProperty("wtm",wtm);
worker.setSharedProperty("mtw",mtw);
worker.start();
wtm.addEventListener(flash.events.Event.CHANNEL_MESSAGE,onChannelMessage);
this.addEventListener(starling.events.Event.ADDED_TO_STAGE, onAddedToStage);
}
protected function onChannelMessage(event:flash.events.Event):void
{
output = wtm.receive();
}
protected function onAddedToStage(event:starling.events.Event):void
{
this.removeEventListener(starling.events.Event.ADDED_TO_STAGE, onAddedToStage);
drawScreen();
}
private function drawScreen():void
{
audioContainer = new Image( Assets.getAtlas().getTexture("audioContainer") );
addChild(audioContainer);
//record button
recButton = new Button( Assets.getAtlas().getTexture("recordButton") );
recButton.x=Math.ceil(194/2 - recButton.width/2);
recButton.y=5;
addChild(recButton);
//stop button
stopButton = new Button( Assets.getAtlas().getTexture("stopButton") );
stopButton.x=recButton.x+10;
stopButton.y=10;
stopButton.visible = false;
addChild(stopButton);
//play button
playButton = new Button( Assets.getAtlas().getTexture("playButton") );
playButton.x=Math.ceil(194 - playButton.width)-25;
playButton.y=10;
playButton.visible = false;
addChild(playButton);
this.addEventListener(starling.events.Event.TRIGGERED, buttons_triggeredHandler);
}
private function buttons_triggeredHandler(event:starling.events.Event):void
{
var currentButton:Button = event.target as Button;
switch(currentButton)
{
case recButton:
startRecording();
break;
case stopButton:
stopRecording();
break;
case playButton:
playRecording();
break;
}
}
private function playRecording():void
{
mtw.send("RECORD_PLAY");
}
private function stopRecording():void
{
stopButton.visible = false;
recButton.x = 25;
playButton.visible = true;
recButton.visible = true;
mtw.send("RECORD_STOP");
//
}
private function startRecording():void
{
recButton.visible = false;
stopButton.visible = true;
playButton.visible = false;
mtw.send("RECORD_START");
}
}
}
RecordWorker
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.media.Microphone;
import flash.system.MessageChannel;
import flash.system.Worker;
import org.as3wavsound.WavSound;
import org.bytearray.micrecorder.MicRecorder;
import org.bytearray.micrecorder.encoder.WaveEncoder;
import org.bytearray.micrecorder.events.RecordingEvent;
public class RecordWorker extends Sprite
{
private var wtm:MessageChannel;
private var mtw:MessageChannel;
// volume in the final WAV file will be downsampled to 50%
private var volume:Number = .75;
// we create the WAV encoder to be used by MicRecorder
private var wavEncoder:WaveEncoder = new WaveEncoder( volume );
// we create the MicRecorder object which does the job
private var recorder:MicRecorder = new MicRecorder( wavEncoder,Microphone.getEnhancedMicrophone() );
public function RecordWorker()
{
wtm = Worker.current.getSharedProperty("wtm");
mtw = Worker.current.getSharedProperty("mtw");
mtw.addEventListener(Event.CHANNEL_MESSAGE,command_Handler);
}
//message received from the main component
protected function command_Handler(event:Event):void
{
switch(mtw.receive())
{
case "RECORD_START":
trace("recording.....");
recorder.record();
recorder.addEventListener(RecordingEvent.RECORDING, onRecording);
recorder.addEventListener(flash.events.Event.COMPLETE, onRecordComplete);
break;
case "RECORD_STOP":
trace("record stopped....");
recorder.stop();
break;
case "RECORD_PLAY":
if(recorder.output.length>0)
{
var player:WavSound = new WavSound(recorder.output);
player.play();
}
break;
}
}
private function onRecording(event:RecordingEvent):void
{
trace ( event.time );
}
private function onRecordComplete(event:flash.events.Event):void
{
}
}
}
anny help will be appriciated
Thanks,
Khaled
Looking at this write-up on Adobe's AS3 reference, it seems that because each created worker is "a virtual instance of the Flash runtime", it has no direct connection to any of the core runtime's input or output channels. The Microphone class is one such cut-off interface, which is why it can't reach the system mic inside a worker.

gallery last image fix

I almost have this thing the way I want it except when I'm clicking forward or backwards through my images, once it hits the array length, the next images doesn't show. It is only an issue when I add the checkImage() method. Anyone see what I have wrong?
fix**
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import com.greensock.TweenMax;
import com.greensock.layout.*;
import com.greensock.loading.LoaderMax;
import com.greensock.loading.XMLLoader;
import com.greensock.loading.ImageLoader;
import com.greensock.events.LoaderEvent;
import com.greensock.loading.display.ContentDisplay;
import com.greensock.loading.data.XMLLoaderVars;
public class Main extends MovieClip
{
public var imgHolder:MovieClip;
private var ls:LiquidStage;
private var la:LiquidArea;
private var xml:XMLLoader;
private var index:int = 0;
private var images:Array;
public function Main()
{
arrowRight.alpha = arrowLeft.alpha = .5;
xmlLoader();
}
private function xmlLoader():void
{
LoaderMax.activate([ImageLoader]);
xml = new XMLLoader("assets/data.xml", new XMLLoaderVars()
.name("loader")
.estimatedBytes(600000)
.onComplete(xmlLoaded)
.onProgress(loadProgress));
xml.load();
}
private function xmlLoaded(e:LoaderEvent):void
{
trace("Loaded");
arrowListeners();
showImage(index);
}
private function loadProgress(event:LoaderEvent):void
{
progressMC.progressBar.scaleX = event.target.progress;
}
private function showImage(index:int):void
{
ls = new LiquidStage(this.stage, 1024, 768, 1024, 768);
la = new LiquidArea(imgHolder, 0, 0, 1024, 768);
images = LoaderMax.getContent("loader");
imgHolder.addChild(images[index]);
TweenMax.from(images[index], 1, {alpha:0});
la.attach(images[index], {scaleMode:ScaleMode.PROPORTIONAL_OUTSIDE, crop:true});
}
// BUTTON FUNCTIONS
private function arrowListeners():void
{
arrowRight.addEventListener(MouseEvent.ROLL_OVER, rollOverArrowHandler, false, 0, true);
arrowRight.addEventListener(MouseEvent.ROLL_OUT, rollOutArrowHandler, false, 0, true);
arrowRight.addEventListener( MouseEvent.CLICK, showNext );
arrowLeft.addEventListener(MouseEvent.ROLL_OVER, rollOverArrowHandler, false, 0, true);
arrowLeft.addEventListener(MouseEvent.ROLL_OUT, rollOutArrowHandler, false, 0, true);
arrowLeft.addEventListener( MouseEvent.CLICK, showPrev );
}
private function rollOverArrowHandler(e:MouseEvent):void
{
TweenMax.to(e.currentTarget, 0.5, {alpha:1});
}
private function rollOutArrowHandler(e:MouseEvent):void
{
TweenMax.to(e.currentTarget, 0.5, {alpha:.5});
}
// CLICK LISTENERS
private function showNext( e:MouseEvent ):void
{
index++
if (index > images.length - 1)
{
index = 0;
}
showImage(index);
}
private function showPrev( e:MouseEvent ):void
{
index--
if (index < 0)
{
index = images.length - 1;
}
showImage(index);
}
}
}
Several things come to mind:
1) index is a global variable and a function param - conflicting?
2) in the checkimage function you pass in 'index' but refer to 0 in getChildAt and RemoveChildAt
3) you don't call showimage in checkimage if the numchildren > 0 is true
I'd want to trace into all of this to sort it out.

AS3 ActionScript 3 - Instantiating Objects With A Timer?

I'm making a vertical (constantly) scrolling shooter & am trying to instantiate objects based on a timer. For example: At 30 seconds, place a building # x, y.
My problem is that the "building" is instantiated when the game starts and then again at the 30 second mark - instead of only # the 30 second mark.
If anyone could steer me in the correct direction, it would be greatly appreciated.
package com.gamecherry.gunslinger
{
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class ObjectPlacer extends MovieClip
{
private var Build01Timer:Timer;
private var canPlace:Boolean = true;
private var stageRef:Stage;
private var startX:Number;
private var startY:Number;
private var time:int = 5000;
public function ObjectPlacer(stageRef:Stage) : void
{
this.stageRef = stageRef;
var Build01Timer = new Timer(time, 1);
Build01Timer.addEventListener(TimerEvent.TIMER, placeTimerHandler, false, 0, true);
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
Build01Timer.start();
}
private function loop(e:Event): void
{
if (canPlace)
{
var BuildingsLeft01:BuildingsLeft = new BuildingsLeft(stage, 720, -540);
BuildingsLeft01.scaleX = -1;
stageRef.addChildAt((BuildingsLeft01), 2);
canPlace = false;
}
}
private function placeTimerHandler(e: TimerEvent) : void
{
canPlace = true;
}
private function removeSelf() : void
{
removeEventListener(Event.ENTER_FRAME, loop);
if (stageRef.contains(this))
stageRef.removeChild(this);
}
}
}
Where am I going wrong?
Thank you for looking.
Here's the first of your class:
public class ObjectPlacer extends MovieClip
{
private var Build01Timer:Timer;
**private var canPlace:Boolean = true;**
You're setting it to TRUE at the start, set it to false, and that would solve your problem :)