Unloading external SWF files - actionscript-3

I'm loading multiple swf files from the main menu which is never unloaded. I've done this with the following code... Only issue is that instead of unloading to the main menu I just see a white screen as if nothing is loaded.
function BackToMenu(i:MouseEvent):void
{
var BaseMovie:MovieClip = parent.parent as MovieClip;
BaseMovie.parent.removeChild(BaseMovie);
}
EDIT: I'll explain from the start I have a MainMenu.swf. The games are loaded from MainMenu.swf when the button relating to the game is clicked. When a game button is clicked on MainMenu.swf the game loads. When the player completes a game they are presented with the exit button which unloads the current game and shows the MainMenu.swf without having to re-load it.

First, you should remove one parent to make sure you are actually removing only the game:
function BackToMenu(i:MouseEvent):void
{
var BaseMovie:MovieClip = parent as MovieClip;
BaseMovie.parent.removeChild(BaseMovie);
}
This should take care of your most pressing problem, and allow you to return to the menu. You have, however, not really unloaded the game, but only removed it from the display list. This often means, that there are still sounds running, active key and/or mouse listeners, etc. - these must all be taken care of!
And, like I said, this will only fix your immediate problem. It is, however, neither a permanent solution, nor a good one: Since the main SWF is responsible for loading the games, it should also be responsible for disposing of them. You should put cleanup code into your game, but it should only be concerned with stopping any running scripts, sounds, etc. - simple rule: anything that is started within the game, should be stopped within the game. But it should not try to access objects further up in the display hierarchy, or try to unload itself.
The much better way to do this is by replacing all the above code, and letting the main SWF take care of removing the game, as well as unloading it from memory. For this, you have to do three things:
Instead of writing actual removeChild calls, etc., let your button dispatch a custom event to notify the main SWF that it should now be removed:
function onBackButtonClicked( event:MouseEvent ):void {
destroyGame(); // this would be the function that stops all the scripts
dispatchEvent( new Event( "FINISH_GAME", true ) );
}
Note that "FINISH_GAME" is now a "bubbling" event, i.e. it travels downward in the display hierarchy. We can now listen for this event in any ancestor display object containing the game.
In your main SWF, add an event listener to the Loader when the game was successfully loaded. This is done in the event listener that is called when the load process completes:
function onLoadComplete( event:Event ):void {
var loader:Loader = event.target.loader;
loader.addEventListener( "FINISH_GAME", onFinishGame, true );
}
Use the corresponding event handler to remove the game clip:
function onFinishGame( event:Event ):void {
var loader:loader = event.currentTarget;
loader.parent.removeChild( loader );
loader.unloadAndStop();
}
A few more things to consider:
The naming conventions in ActionScript advise us to use lower case names for methods and variables, and upper case only for types.
The same naming conventions suggest we use either "on" or "handle" as a prefix for event listeners, along with the name of the event. Thus, it should be onBackToMenu or rather, onBackButtonClicked, etc.
Since I don't know anything about the code you use for loading, I just assumed you have a complete listener, and you don't keep references to the loader. If you use a member variable, you can use that instead of event.target, resp. event.currentTarget.

Related

CreateJS way of switching ticker on & off

I'm developing a canvas game that happens to have several scenes. Each scene might end up being a static final frame after having finished. The circumstances are that the ticker and the listener for the "tick" event are still running and keep on rendering full speed - which is asking for cpu usage.
I have tried to remove the listeners at the end of scene and add them back wenn the user interacts and starts the next scene.
I wonder what would be the "createJS" way of doing this.
I see some other options but am a bit lost how to proceed:
Caching the "whole" last frame. Will it make the ticker do "absolutely nothing" performance-wise?
Pause the ticker and check for the paused attribute in the handleTick method: Seems to not take the CPU usage completely down.
Can somebody recommend a way?
On a side note: I need my real "this" object inside the tick function that is bound to the ticker. How can I achieve this? Right now I use this code:
createjs.Ticker.addEventListener("tick", handleTick);
function handleTick(event) {
// Actions carried out each tick (aka frame)
if (!event.paused) {
// Actions carried out when the Ticker is not paused.
}
}
Inside handleTick "this" is not my object that added the listener.
A simple createjs.Ticker.removeEventListener("tick", handleTick); should do just fine as long as handleTick exists in your current scope. See this example.
There are a couple ways to access the scope of the object that assigned the tick listener. For example, you could simply assign this to a local variable like so:
var _this = this;
function handleTick(){
//"_this" now refers to the scope that defined handleTick.
}
Or you can use a delegate. In this example I'm using jQuery's proxy function to scope handleTick to this.
var handleTick = $.proxy(function(){
//"this" refers to the scope that defined handleTick.
}, this);
createjs.Ticker.addEventListener("tick", tickHandler);

When the game of an external swf is finished, remove the external swf

I am creating a series of mini games and animations and plan on bringing them all into one flash file. Each of the games need to disappear when the player has finished them. I don't know what to put into the section in the external swfs when the game is done. I currently just have a trace ("finished").
In my main swf you should click start and a game swf appears and when you are finished it, it should disappear.
I have looked up tutorials and they something about accessing variables in the external swfs but I got nowhere with them.
in place of trace("finished");, dispatch something like a complete event:
dispatchEvent(new Event(Event.COMPLETE));
Then listen for that event in the container swf and respond appropriately.
Here is an example for the host (parent) swf:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,loadDone, false,0,true);
loader.load(new URLRequest("temp2.swf"));
function loadDone(e:Event){
trace("CONTENT LOADED");
addChild(loader.content);
loader.content.addEventListener(Event.COMPLETE,go,false,0,true); //listen on the capture phase (third parameter true) if you're complete event is NOT on the main timeline of your child swf
}
function go(e:Event):void {
trace("Content is all done");
removeChild(loader.content);
loader.unloadAndStop(); //tries to free the app of all memory used by the loaded swf
loader = null;
}
Another way, is in place of trace("finished"), you could have the child swf remove itself (as per a comment on the question). I would consider this a less desirable solution (though more encapsulated) as it lessens re usability and will likely still leave the swf in memory:
stop();
if(this.parent){
this.parent.removeChild(this);
}

as3 Air - AddChild works but is slooooooooooow

I am creating an app where when a button is pressed a very large picture is added to the stage (it is larger than the screen but can be dragged around by the user)
When the button is pressed the picture (well, movieClip) does come up and it able to be dragged fine, buttons inside it work.
The problem though is that there is a pause of about 6 seconds between the button press and the image appearing. I am using one .fla file for publishing and compiling (let's just call it Main.fla for now), and another one to hold all the graphics. The graphics are then added with this embed command:
[Embed (source = "assets/graphic.swf", symbol = "Content")]
private var Content:Class;
private var _content:*;
I have these lines where all the variables are declared (in between the class definition and the constructor function) I was under the impression that embedding it like this was equivalent to loading it at compile time. Is this true? What could be causing this lag when the button is pressed?
If I can't cut out the lag, another idea I had was to make some spinning circle or something to tell the user, "hey, don't worry. It's loading!"
If the slowness is at addChild you can add the asset to the stage much earlier and set it's visiblility to false, then when the button is clicked set it back to true. Obviously this is a small hack but might be sufficient for what you are doing.
var asset:MovieClip;
private function init():void
{
asset = new Content();
assset.visible = false;
addChild(asset);
button.addEventListener(MouseEvent.CLICK, onMouseClick);
}
private function onMouseClick(e:MouseEvent):void
{
asset.visible = true;
}
Embedding your SWF is probably not what is causing the delay.. or rather it would not likely be better if you imported the SWF into your FLA. Is this on a device? Chances are you would either have to devise a different way of loading your asset, or be satisfied with a loading animation.
If the main K size is coming from a large image, you could consider loading it in segments, starting with the part that is initially visible.

How do I restart flash application with actionscript 3

yeah, I need to restart my application, my actioscript 3 code or at least remove all the content in stage to upload the beginning.
This is not movie, so playing with gotoandplays is not an option.
Thanks!
Best practice would be for each object that carries a strong listener to also listen for the Event.REMOVED_FROM_STAGE event, and destroy all its listeners and handle the properties you wish to save.
while(numChildren) removeChildAt(0);
Called from the root (or main timeline) will remove all symbols from the current container in scope. I assume what you're calling it in is added to the display list, so
while(MovieClip(root).numChildren) MovieClip(root).removeChildAt(0);
Is appropriate code.
First structure design.
For example: make a gameContainer the sprite variable add to stage. while the game progresses, all object add gameContainer. When the game is ended, remove the event, you do not need to remove all the objects. And calls the function that default settings you have made that.
// removeEventListener
// removeAllObjects about following
while (gameContainer.numChildren)
{
   gameContainer.removeChildAt (0);
}

Actionscript to play/pause audio on different buttons

I've created a few buttons in Flash. I'm trying to make it so that if you click one button, the audio starts playing for that button. If you click another button, the active audio stops and the new audio of the button you clicked last start playing.
Any help please?
What you're describing is actually quite easy to do.
First things first, I recommend importing the audio into your Flash project. Alternatively, there is a way to play it directly from an external file. This is beyond the scope of my answer, so if you need help on that, you should post a question specifically covering it.
Assuming you have imported the audio file into your Flash project's library, make an as3 instance of it. (Right click the file in the library, click Properties --> ActionScript [tab] --> [Check] Export for ActionScript & [Enter name in] Class)
Now, create a definition of the sound in your code. (Assuming your two sounds were named "mySound1" and "mySound2" in the Class field of the previous step.)
var mySound1:Sound = new mySound1();
var mySound2:Sound = new mySound2();
Now, define your sound channel.
var mySoundChannel:SoundChannel = new SoundChannel();
There are two alternate ways of stopping one sound and playing another. The first is to create one function that does both every time. The second method is to create two formulas, one for "play" and one for "stop". You will need to decide which method works best for you. I'll use the two-function method below:
function stopSound():void
{
//This stops all sound in the sound channel.
//If there is nothing playing, nothing happens.
mySoundChannel.stop();
}
//In this function, we create an argument that allows us to tell the function
//what sound to we want it to play.
function playSound(soundname:String):void
{
mySoundChannel = this[soundname].play(0, 0);
}
[Note, you can tweak the play() properties to meet your needs, doing things like starting in the middle of the song, or looping it forever. 0,0 starts at the beginning, and doesn't loop. See the documentation for this.]
Now you hook up the event listeners for the buttons. (If you need help with event listeners, read the documentation.)
myButton1.addEventListener(Mouse.CLICK, btn1Click);
myButton2.addEventListener(Mouse.CLICK, btn2Click);
function btn1Click(evt:Event):void
{
stopSound();
playSound(mySound1);
}
function btn2Click(evt:Event):void
{
stopSound();
playSound(mySound2);
}
This should be enough information to get you started. In my game core, I actually have a custom class for dealing with sound playback that gives me the ability to repeat sounds, change volume, and keep sounds from conflicting with each other. I say that to emphasize that you can do quite a bit with the sound class. Do some digging in that documentation for ideas and help.
You may also consider putting a try-catch statement in the playSound function, since it will throw an reference error if you pass a name for a sound that doesn't exist.