I made a code for preloader that worked when it was written in frame actions. But then I decided to move all the code to classes and a bit reworked it. And now it doesn't work. Function that listener should call is just not called, and I started getting errors when address to argument event in this not-called function.
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.ProgressEvent;
public class Preloader extends MovieClip {
public function Preloader() {
addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event):void {
trace("init started");
removeEventListener(Event.ADDED_TO_STAGE, init);
loaderInfo.addEventListener(ProgressEvent.PROGRESS, showProgress);
trace("init completed");
}
private function showProgress(e:Event):void {
trace(loaderInfo.bytesLoaded);
/*info_txt.text = Math.floor(e.bytesLoaded/e.bytesTotal*100) + "%"
if (e.bytesLoaded==e.bytesTotal) {
loaderInfo.removeEventListener(ProgressEvent.PROGRESS, showProgress);
finalizeLoading();
}
/**/
}
private function finalizeLoading():void {
removeChild(info_txt);
var startGame_btn = new StartGame_btn();
addChild(startGame_btn);startGame_btn.x=395;startGame_btn.y=290;
}
}
}
When I uncomment /*info_txt... part. I get this:
Access of possibly undefined property bytesLoaded through a reference with static type flash.events:Event.
Access of possibly undefined property bytesTotal through a reference with static type flash.events:Event.
Access of possibly undefined property bytesLoaded through a reference with static type flash.events:Event.
Access of possibly undefined property bytesTotal through a reference with static type flash.events:Event.
Change loaderInfo to root.loaderInfo in the init method for listening root loaderInfo object. When your script were in timeline this object were documentClass and root simultaneously, so your code have worked properly.
What about errors, just change type of e argument from Event to ProgressEvent in the showProgress method, because Event doesn't gave such properties.
There is a lot wrong with your code.
Here is a simple loader with some of your code added. at the worst it should point you in the right direction.
package {
import flash.display.MovieClip;
import flash.errors.IOError;
import flash.events.AsyncErrorEvent;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
public class myPreloader extends MovieClip {
public var context:LoaderContext = new LoaderContext();
public var myLoader:Loader = new Loader();
public var url:URLRequest;
public function myPreloader() {
context = new LoaderContext();
context.checkPolicyFile = true;
myLoader = new Loader();
myLoader.addEventListener(AsyncErrorEvent.ASYNC_ERROR, errorHandlerAsyncErrorEvent);
myLoader.addEventListener(IOErrorEvent.IO_ERROR, errorHandlerIOErrorEvent);
myLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandlerSecurityErrorEvent);
myLoader.contentLoaderInfo.addEventListener(Event.INIT, initHandler);
myLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, infoIOErrorEvent);
myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressListener);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
url = new URLRequest("test.swf"); // change this to whatever it is you are loading
myLoader.load( url,context );
myLoader.load( url);
}
public function progressListener (e:ProgressEvent):void{
trace("Downloaded " + e.bytesLoaded + " out of " + e.bytesTotal + " bytes");
info_txt.text = info_txt.text = Math.floor(e.bytesLoaded/e.bytesTotal*100) + "%"
}
public function onLoadComplete( e:Event ):void{
trace( 'onLoadComplete' );
removeChild(info_txt);
var startGame_btn = new StartGame_btn();
addChild(startGame_btn);
startGame_btn.x = 395;
startGame_btn.y=290;
}
public function initHandler( e:Event ):void{
trace( 'load init' );
}
public function errorHandlerErrorEvent( e:ErrorEvent ):void{
trace( 'errorHandlerErrorEvent ' + e.toString() );
}
public function infoIOErrorEvent( e:IOErrorEvent ):void{
trace( 'infoIOErrorEvent ' + e.toString() );
}
public function errorHandlerIOErrorEvent( e:IOErrorEvent ):void{
trace( 'errorHandlerIOErrorEvent ' + e.toString() );
}
public function errorHandlerAsyncErrorEvent( e:AsyncErrorEvent ) :void{
trace( 'errorHandlerAsyncErrorEvent ' + e.toString() );
}
public function errorHandlerSecurityErrorEvent( e:SecurityErrorEvent ):void{
trace( 'errorHandlerSecurityErrorEvent ' + e.toString() );
}
}
}
Related
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.
Ive just finished the basic structure of a little game and saved the simple preloader till last. Silly me.
After numerous tutorials I found this one that worked for me - Pre Loader in Flash Builder
The preloader works and the game is on the stage, but freezes instantly. Any reference to the stage in my LevelOne code throws up errors. error #1009: cannot access a property or method of a null object reference.
Before implementing the Preloader, my Application Class (RookiesGame) was used as a level switcher. Each level is contained in a Sprite. RookiesGame starts by adding LevelOne to stage, then once player completes it, RookiesGame removes LevelOne and adds LevelTwo to stage etc.
The level classes reference the stage with the _stage variable.
Since Ive been learning this structure, the preloader becoming the application class and RookiesGame becoming just another class has really confused me. Shouldn’t the _stage var still work? Is it okay to keep RookiesGame as a level switcher?
Anyway main problem is referencing the stage from the Level Classes.
Current code:
Preloader Class
Works fine, game starts.
package
{
import flash.display.DisplayObject;
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.utils.getDefinitionByName;
[SWF(width="650", height="450", backgroundColor="#FFFFFF", frameRate="60")]
public class Preloader extends Sprite
{
// Private
private var _preloaderBackground:Shape
private var _preloaderPercent:Shape;
private var _checkForCacheFlag:Boolean = true;
// Constants
private static const MAIN_CLASS_NAME:String = "RookiesGame";
public function Preloader()
{
trace("Preloader: Initialized.")
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
public function dispose():void
{
trace("Preloader: Disposing.")
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
if (_preloaderBackground)
{
removeChild(_preloaderBackground);
_preloaderBackground = null;
}
if (_preloaderPercent)
{
removeChild(_preloaderPercent);
_preloaderPercent = null;
}
}
// Private functions
private function onAddedToStage(e:Event):void
{
trace("Preloader: Added to stage.");
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.scaleMode = StageScaleMode.SHOW_ALL;
stage.align = StageAlign.TOP_LEFT;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(e:Event):void
{
if (_checkForCacheFlag == true)
{
_checkForCacheFlag = false;
if (root.loaderInfo.bytesLoaded >= root.loaderInfo.bytesTotal)
{
trace("Preloader: No need to load, all " + root.loaderInfo.bytesTotal + " bytes are cached.");
finishedLoading();
}
else
beginLoading();
}
else
{
if (root.loaderInfo.bytesLoaded >= root.loaderInfo.bytesTotal)
{
trace("Preloader: Finished loading all " + root.loaderInfo.bytesTotal + " bytes.");
finishedLoading();
}
else
{
var percent:Number = root.loaderInfo.bytesLoaded / root.loaderInfo.bytesTotal;
updateGraphic(percent);
trace("Preloader: " + (percent * 100) + " %");
}
}
}
private function beginLoading():void
{
// Might not be called if cached.
// ------------------------------
trace("Preloader: Beginning loading.")
_preloaderBackground = new Shape()
_preloaderBackground.graphics.beginFill(0x333333)
_preloaderBackground.graphics.lineStyle(2,0x000000)
_preloaderBackground.graphics.drawRect(0,0,200,20)
_preloaderBackground.graphics.endFill()
_preloaderPercent = new Shape()
_preloaderPercent.graphics.beginFill(0xFFFFFFF)
_preloaderPercent.graphics.drawRect(0,0,200,20)
_preloaderPercent.graphics.endFill()
addChild(_preloaderBackground)
addChild(_preloaderPercent)
_preloaderBackground.x = _preloaderBackground.y = 10
_preloaderPercent.x = _preloaderPercent.y = 10
_preloaderPercent.scaleX = 0
}
private function updateGraphic(percent:Number):void
{
// Might not be called if cached.
// ------------------------------
_preloaderPercent.scaleX = percent
}
private function finishedLoading():void
{
var RookiesGame:Class = getDefinitionByName(MAIN_CLASS_NAME) as Class;
if (RookiesGame == null)
throw new Error("Preloader: There is no class \"" + MAIN_CLASS_NAME + "\".");
var main:DisplayObject = new RookiesGame() as DisplayObject;
if (main == null)
throw new Error("Preloader: The class \"" + MAIN_CLASS_NAME + "\" is not a Sprite or MovieClip.");
addChild(main);
dispose();
}
}
}
RookiesGame Class (used to be application class)
Any references to the stage threw up #1009 error, which stopped when I changed stage.addChild to this.addChild
Ive not got to the level switch handler yet with the preloader, so I dont know how stage.focus will work either!
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
public class RookiesGame extends Sprite
{
private var _levelOne:LevelOne;
private var _levelTwo:LevelTwo;
public function RookiesGame()
{
_levelOne = new LevelOne(stage);
_levelTwo = new LevelTwo(stage);
this.addChild(_levelOne);
this.addEventListener("levelOneComplete",levelTwoSwitchHandler);
}
private function levelTwoSwitchHandler(event:Event):void
{
this.removeChild(_levelOne);
_levelOne = null;
this.addChild(_levelTwo);
stage.focus = stage;
}
}
}
LevelOne Class
Lots of #1009 errors. Anything referencing the stage.
Class is huge so I'll highlight problem chunks.
The #1009 error when referencing stage, adding the keyboard listeners.
_stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
_stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
Also #1009 when referencing stage to check stage Boundaries. Cant just change stage. to this. anymore.
private function checkStageBoundaries(gameObject:MovieClip):void
{
if (gameObject.x < 50)
{
gameObject.x = 50;
}
if (gameObject.y < 50)
{
gameObject.y = 50;
}
if (gameObject.x + gameObject.width > _stage.stageWidth - 50)
{
gameObject.x = _stage.stageWidth - gameObject.width - 50;
}
if (gameObject.y + gameObject.height > _stage.stageHeight - 50)
{
gameObject.y = _stage.stageHeight - gameObject.height - 50;
}
}
I reference _stage later in the program to remove the event listeners. Thats it.
_stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
_stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
How can I reference the stage, without these errors and keep RookiesGame as the level switcher.
LevelOne Class Structure
To show how I use(d) _stage.
package
{
//import classes
public class LevelOne extends Sprite
{
//Declare the variables to hold the game objects
//A variable to store the reference to the stage from the application class
private var _stage:Object;
public function LevelOne(stage:Object)
{
_stage = stage;
this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}
private function addedToStageHandler(event:Event):void
{
startGame();
this.removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}
private function startGame():void
{
//Includes _stage references that mess everything up.
}
private function levelCleared():void
{
//When Level finished, dispatch event to tell RookiesGame to switch levels.
dispatchEvent(new Event("levelOneComplete", true));
}
}
}
Sorry if thats confusing, but if you can help me reference the stage via LevelOne and RookiesGame classes, It would be much appreciated.
You are passing in a null stage to LevelOne from your RookiesGame class. Whenever you instantiate a RookiesGame the constructor will run first, it has not been added to the display list yet so its inherited reference to stage is null. What you need to do is add an event listener for ADDED_TO_STAGE in the RookiesGame class:
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
public class RookiesGame extends Sprite
{
private var _levelOne:LevelOne;
private var _levelTwo:LevelTwo;
public function RookiesGame()
{
addEventListener( Event.ADDED_TO_STAGE, onAdded );
}
//added to stage event
private function onAdded( e:Event ):void {
removeEventListener( Event.ADDED_TO_STAGE, onAdded );
_levelOne = new LevelOne(stage);
_levelTwo = new LevelTwo(stage);
this.addChild(_levelOne);
this.addEventListener("levelOneComplete",levelTwoSwitchHandler);
}
...
}
Also if you are using addChild() call for LevelOne as in addChild(_levelOne) it has its own reference to stage after it's been added to the display list, you do not need to create a _stage variable for those classes if you are adding them to the display list.
Also you have the listener for ADDED_TO_STAGE in LevelOne, where the stage variable would have no longer been null, so you can remove your class variable _stage entirely.
I have a class calling a function in another class. I want to know
if we can add an Event Listener to know if that function has fired and is finished etc.
Here is the section of the code that is relevant.
myMC = new pictures();
addChild(myMC);
myMC.loadImages("Joyful",1)
// Add Event Listener here to let me know loadImages was called and worked.
As you can see the function is called loadImages() and it is located in a class called pictures.as
Can I add an event listener to this?
Here is a new issue. I am using a similar method and I used your example below and it did not work. Am I missing an import or something? I am only showing the functions that pertain and not my whole script.
Main.class
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.display.*;
import flash.filesystem.*;
import com.greensock.*;
import com.greensock.easing.*;
import flash.system.System;
// Ed's Scripts
import com.*;
import com.views.*;
public class iRosaryMain extends MovieClip
{
/// (Get Main Doc flow) this creates an instace of the main timeline
/// and then I send it
private static var _instance:iRosaryMain;
public static function get instance():iRosaryMain
{
return _instance;
}
/// Declaring Vars
var audio:audioPrayers;
/// Loading Images
//public var theImages:pictures = new pictures();
/// Movie Clips
public var myMary:beautifulMary;
public var myMC:MovieClip;
public var myPic:MovieClip;
public var myFlags:MovieClip;
public static var mt:MovieClip;
var vars:defaultVars = new defaultVars();
public function iRosaryMain()
{
// (Get Main Doc flow) Here I send the an instacne of iRosaryMain to defaultVars.as
_instance = this;
vars.getMainDoc(_instance);
// Sets timeline to mt :) I hope
mt = _instance;
audio = new audioPrayers();
trace("Jesus I trust in you!");// constructor code
audio.sayHailMary();
if (stage)
{
init();
}
}
public function moveLanguages()
{
/// File to languages folder
var checkLanguageFolder:File = File.applicationStorageDirectory.resolvePath("Languages");
///// CHECK LANGUAGES FOLDER - if not in App Storage move it
if (! checkLanguageFolder.exists)
{
var sourceDir:File = File.applicationDirectory.resolvePath("Languages");
var resultDir:File = File.applicationStorageDirectory.resolvePath("Languages");
sourceDir.copyTo(resultDir, true);
trace( "Moved Language!");
}
}
//// MAIN FUNCTIONS IN iRosaryMainClass
function init()
{
//loadFlags();
moveLanguages();
//addChild(theImages);
intro();
}
public function loadFlags()
{
myFlags.addEventListener("MyEvent", eventHandler);
myFlags = new viewLanguages();
addChild(myFlags);
myFlags.x = stage.stageWidth / 2 - myFlags.getBounds(this).width / 2;
function eventHandler()
{
trace("yes loaded");
TweenMax.fromTo(myMary,3, {alpha:1}, {alpha:0, ease:Quint.easeOut, onComplete: closePic} );
}
}
function intro()
{
myMary = new beautifulMary();
addChild(myMary);
loadFlags();
}
public function closePic()
{
removeChild(myMary);
}
public function languageLoaded(lang:String)
{
trace("YES... " + lang);
homeIn();
}
public function homeIn()
{
if (myFlags)
{
TweenMax.fromTo(myFlags,1, {x:myFlags.x}, {x:0-myFlags.width, ease:Quint.easeInOut, onComplete:unloadMyFlags} );
}
function unloadMyFlags()
{
trace("Called Ease out");
if (myFlags is MovieClip)
{
//trace("CURRENT DISPLAY " + currentDisplayScreen);
trace("CURRENT mc " + myFlags);
removeChild(myFlags);
System.gc();
myFlags = null;
trace("CURRENT mc " + myFlags);
}
}
if (! myMC)
{
myMC = new viewHome();
myMC.name = "Home";
myMC.x = stage.stageWidth / 2 - myMC.width / 2;
addChild(myMC);
}
theEaseIn(myMC);
//Home.B1.addEventListener(MouseEvent.CLICK, theEaseOut(Home));
}
public function loadLanguage(Language:String):Function
{
return function(e:MouseEvent):void ;
{
trace("Did it work? " +Language);
vars.loadButtonVars(Language);;
};
//TweenMax.fromTo(EnglishButton,1, {x:EnglishButton.x}, {x:0-EnglishButton.width, ease:Quint.easeOut} );
}
public function loadView(screen:String)
{
trace("Received " + screen);
if (screen=="Home")
{
myMC = new viewHome();
addChild(myMC);
theEaseIn(myMC);
//Home.B1.addEventListener(MouseEvent.CLICK, theEaseOut(Home));
}
if (screen=="PrayTheRosary")
{
myMC = new viewPrayTheRosary();
addChild(myMC);
theEaseIn(myMC);
//Home.B1.addEventListener(MouseEvent.CLICK, theEaseOut(Home));
}
if (screen=="Options")
{
myMC = new viewOptions();
addChild(myMC);
theEaseIn(myMC);
}
if (screen=="Downloads")
{
myMC = new viewDownloads();
addChild(myMC);
theEaseIn(myMC);
}
if (screen=="beautifulMary")
{
myMC = new beautifulMary();
addChild(myMC);
theEaseIn(myMC);
}
if (screen=="Flags")
{
myFlags = new viewLanguages();
addChild(myFlags);
theEaseIn(myFlags);
}
if (screen=="Joyful" || screen=="Sorrowful" || screen=="Glorious" || screen=="Luminous")
{
myPic = new pictures();
addChild(myPic);
myPic.addEventListener( "ImagesLoaded", doTheEaseIn);
myPic.loadImages(""+screen+"",1);
function doTheEaseIn()
{
theEaseIn(myPic);
}
}
}
public function theEaseIn(mc:MovieClip)
{
if (myMC)
{
TweenMax.fromTo(mc,1, {x:stage.stageWidth+mc.width}, {x:stage.stageWidth/2 - mc.width/2, ease:Quint.easeInOut} );
}
}
public function theEaseOut(mc:MovieClip,nextMC:String):Function
{
return function(e:MouseEvent):void ;
{
loadView(nextMC);
/// Tweens out view on screen
TweenMax.fromTo(mc,1, {x:mc.x}, {x:0-mc.width, ease:Quint.easeInOut, onComplete:unloadMC} );
function unloadMC();
{
trace("Called Ease out");
if(mc is MovieClip);
{
//trace("CURRENT DISPLAY " + currentDisplayScreen);
trace("CURRENT mc " + mc);
removeChild(mc);
System.gc();
myMC = null;
trace("CURRENT mc " + mc);
};
};
};/// end return
}
////////////
}/// End iRosaryMain
}// End Package
viewLanguages.as
package com.views
package com.views
{
import flash.display.MovieClip;
import flash.filesystem.File;
import com.roundFlag;
import flash.events.*;
import flash.display.*;
public class viewLanguages extends MovieClip
{
var Flag:MovieClip;
//public static const FLAGS_LOADED:String = "flagsLoaded";
public function viewLanguages()
{
getLang();
}
function numCheck(num:int):Boolean
{
return (num % 2 != 0);
}
/// Get for App Opening
public function getLang()
{
/// When Live
var folderLanguages:File = File.applicationStorageDirectory.resolvePath("Languages");
var availLang = folderLanguages.getDirectoryListing();
var Lang = new Array();
var LangPath = new Array();
var fl:int = 0;
for (var i:uint = 0; i < availLang.length; i++)
{
if (availLang[i].isDirectory)
{
//flag = new Loader();
//flag.load(new URLRequest(File.applicationStorageDirectory.url + "Languages/" + Lang[i] + "/roundFlag.png"));
Lang.push(availLang[i].name);
LangPath.push(availLang[i].nativePath);
Flag = new roundFlag(availLang[i].name);
Flag.name = availLang[i].name;
if (numCheck(i)==false)
{
Flag.y = fl;
Flag.x = 0;
}
else
{
Flag.y = fl;
Flag.x = Flag.width + 33;
fl = fl + Flag.height + 33;
}
Flag.btext.text = availLang[i].name;
addChild(Flag);
trace(availLang[i].nativePath);// gets the name
trace(availLang[i].name);
}
}
trace("Get Lang Called");
dispatchEvent(new Event("MyEvent"));
}
}
}
Yes, you can. Considering you are adding your clip to the display list I assume it extends either Movieclip or Sprite, both of which extend EventDispatcher. In your pictures class you can simply use dispatchEvent(new Event("MyEvent"); to dispatch an event. Then you could add myMC.addEventListener("MyEvent", eventHandler); to react to it.
You should also not use strings for events like I wrote above. It would be better if you declared a public static const IMAGES_LOADED:String = "imagesLoaded"; in your pictures class. Then you should use this constant by dispatching and by listening to it.
EDIT: Here how it would look with the constant:
//your class
package {
import flash.events.Event;
import flash.display.Sprite;
public class Pictures extends Sprite {
public static const IMAGES_LOADED:String = "imagesLoaded";
public function Pictures() {
}
public function onAllImagesLoaded():void {
dispatchEvent(new Event(IMAGES_LOADED));
}
//rest of your methods
}
}
//you would call it like this:
var myMc:Pictures = new Pictures();
myMc.addEventListener(Pictures.IMAGES_LOADED, onImagesLoaded);
myMc.loadImages();
function onImagesLoaded(e:Event):void {
//...etc
}
You have to create custom event class for this to work. Like:
package com.some
{
import flash.events.Event;
public class SomeEvent extends Event
{
// Loading events
public static const MAINDATA_LOADING:String = "onMainDataLoading";
// Other event
public static const SOME_LOADING:String = "onSomeLoading";
public var params:Object;
public function SomeEvent($type:String, $params:Object, $bubbles:Boolean = false, $cancelable:Boolean = false)
{
super($type, $bubbles, $cancelable);
this.params = $params;
}
public override function clone():Event
{
return new SomeEvent(type, this.params, bubbles, cancelable);
}
}
}
Add event dispatch inside wanted class (Pictures) and pass wanted params to event (this or any else)
dispatchEvent(new SomeEvent(SomeEvent.IMAGES_LOADED, this));
Handle event listening:
var myMc:Pictures = new Pictures();
myMc.addEventListener(SomeEvent.IMAGES_LOADED, onImagesLoaded);
myMc.loadImages();
function onImagesLoaded(e:SomeEvent):void {
// handle event.
var picts:Pictures = (e.params as Pictures);
}
I got a variable
var Something = "Text";
i want to import Text .as that is placed in abc folder
so what can i do? I tried writing :
import abc.Something;
Doesn't work, any help?
Btw the main point again, i want to import Text
What you trying to do will not work. The import statement is for classes. You could define your text string in a static variable and then use this variable in your code. Be aware, this is not good design.
package abc{
public class TextHolder
{
public static var something:String = "Text";
}
}
in another class:
package {
import abc.TextHolder
public class Main
{
var text:String = TextHolder.something;
}
}
You could also use the include statement. With this statment you can include as files in to your current file
include "abc.script.as"
The variable in this script will then be included in the current script.
What you really want, I guess is to load text and other resources at runtime.
You can simply do that with the URL Loader.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLLoader.html
This example is from the adobe livedocs
package {
import flash.display.Sprite;
import flash.events.*;
import flash.net.*;
public class URLLoaderExample extends Sprite {
private loader:URLoader;
public function URLLoaderExample() {
loader = new URLLoader();
configureListeners(loader);
var request:URLRequest = new URLRequest("urlLoaderExample.txt");
try {
loader.load(request);
} catch (error:Error) {
trace("Unable to load requested document.");
}
}
private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
private function completeHandler(event:Event):void {
var loader:URLLoader = URLLoader(event.target);
trace("completeHandler: " + loader.data);
var vars:URLVariables = new URLVariables(loader.data);
trace("The answer is " + vars.answer);
}
private function openHandler(event:Event):void {
trace("openHandler: " + event);
}
private function progressHandler(event:ProgressEvent):void {
trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function httpStatusHandler(event:HTTPStatusEvent):void {
trace("httpStatusHandler: " + event);
}
private function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event);
}
}
}
Its a little bit to much but covers the whole process of loading ascii data.
I'm trying to get the youtube as3 chromeless player to work. I have followed the youtube as3 API examples and this is what i got so far:
public class Main extends Sprite
{
Security.allowDomain("*");
private var player:Sprite;
private var loader:Loader;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
}
private function onLoaderInit(e:Event):void
{
player = Sprite(loader.content);
addChild(player);
player.addEventListener("onReady", onPlayerReady);
player.addEventListener("onError", onPlayerError);
player.addEventListener("onStateChange", onPlayerStateChange);
player.addEventListener("onPlayerQualityChange", onVideoPlaybackQualityChange);
}
private function onPlayerReady(e:Event):void
{
trace("Player ready: " + Object(e.target).Data);
// player.loadVideoById("uad17d5hR5s");
}
private function onPlayerError(e:Event):void
{
trace("Player error: " + Object(e).Data);
}
private function onPlayerStateChange(e:Event):void
{
// trace("Player state: " + Object(e).Data);
}
private function onVideoPlaybackQualityChange(e:Event):void
{
trace("Video quality: " + Object(e).Data);
}
}
The onPlayerReady and the onStateChange events fires but i get errors. When tracing Object(e).Data i get this error:ReferenceError: Error #1069: the property Data was not found for com.google.youtube.event.ExternalEvent and there is no standard value.(stranslated from swedish)
When changing to Object(e.target).Data it traces "undefined" and Object(e.target) traces "[object SwfProxy]".
If i try player.loadVideoById("uad17d5hR5s"); i get this error:
1061: Call to a possibly undefined method loadVideoById through a reference with static type flash.display:Sprite.
I don't think you should cast loader.content as a Sprite. You should cast the player to an Object type instead. The player variable is only to access the API calls. In terms of placing, moving and adding to the display list, use the Loader object that contains the SwfProxy object. Try this code:
package
{
import flash.display.*;
import flash.events.*;
import flash.system.Security;
import flash.net.*;
public class Main extends MovieClip
{
Security.allowDomain("*");
private var player:Object;
private var loader:Loader;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
}
private function onLoaderInit(e:Event):void
{
player = Sprite(loader.content);
addChild(loader);
player.addEventListener("onReady", onPlayerReady);
player.addEventListener("onError", onPlayerError);
player.addEventListener("onStateChange", onPlayerStateChange);
player.addEventListener("onPlayerQualityChange", onVideoPlaybackQualityChange);
}
private function onPlayerReady(e:Event):void
{
trace("Player ready: " + Object(e.target).Data);
player.loadVideoById("uad17d5hR5s");
player.setSize(480, 365);
}
private function onPlayerError(e:Event):void
{
trace("Player error: " + Object(e).Data);
}
private function onPlayerStateChange(e:Event):void
{
// trace("Player state: " + Object(e).Data);
}
private function onVideoPlaybackQualityChange(e:Event):void
{
trace("Video quality: " + Object(e).Data);
}
}
}