Air App running in DVD - actionscript-3

I created and Air App and published as Application with Run-time Embedded and it's profile is Extended Desktop. Using Flash Professional CC. It consist of menus, quizzes and mp4 videos. Videos are loaded with Netconnection. Everything works fine if I run the app on my pc, however, If I burn the files to a DVD or copy them to a thumb drive, videos or video player controls are not showing at all. The rest of the app is working fine in DVD and in a thumb drive(Menus,quizzes,opening external PDF Files, etc.) Just the videos are not showing up.
// ###############################
// ############# CONSTANTS
// ###############################
// time to buffer for the video in sec.
const BUFFER_TIME:Number = 8;
// start volume when initializing player
const DEFAULT_VOLUME:Number = 0.6;
// update delay in milliseconds.
const DISPLAY_TIMER_UPDATE_DELAY:int = 10;
// smoothing for video. may slow down old computers
const SMOOTHING:Boolean = true;
// ###############################
// ############# VARIABLES
// ###############################
// flag for knowing if user hovers over description label
var bolDescriptionHover:Boolean = false;
// flag for knowing in which direction the description label is currently moving
var bolDescriptionHoverForward:Boolean = true;
// flag for knowing if flv has been loaded
var bolLoaded:Boolean = false;
// flag for volume scrubbing
var bolVolumeScrub:Boolean = false;
// flag for progress scrubbing
var bolProgressScrub:Boolean = false;
// holds the number of the active video
var intActiveVid:int;
// holds the last used volume, but never 0
var intLastVolume:Number = DEFAULT_VOLUME;
// net connection object for net stream
var ncConnection:NetConnection;
// net stream object
var nsStream:NetStream;
// object holds all meta data
var objInfo:Object;
// shared object holding the player settings (currently only the volume)
var shoVideoPlayerSettings:SharedObject = SharedObject.getLocal("playerSettings");
// url to flv file
var strSource:String = root.loaderInfo.parameters.playlist == null ? "video/playlist.xml" : root.loaderInfo.parameters.playlist;
// timer for updating player (progress, volume...)
var tmrDisplay:Timer;
// loads the xml file
var urlLoader:URLLoader;
// holds the request for the loader
var urlRequest:URLRequest;
// playlist xml
var xmlPlaylist:XML;
// ###############################
// ############# FUNCTIONS
// ###############################
// sets up the player
function initVideoPlayer():void {
// hide video controls on initialisation
mcVideoControls.visible = false;
// hide buttons
//mcVideoControls.btnUnmute.visible = false;
//mcVideoControls.btnPause.visible = false;
mcVideoControls.btnFullscreenOff.visible = false;
// set the progress/preload fill width to 1
mcVideoControls.mcProgressFill.mcFillRed.width = 1;
mcVideoControls.mcProgressFill.mcFillGrey.width = 1;
// set time and duration label
mcVideoControls.lblTimeDuration.htmlText = "<font color='#ffffff'>00:00</font> / 00:00";
// add global event listener when mouse is released
stage.addEventListener(MouseEvent.MOUSE_UP, mouseReleased, false, 0, true);
// add fullscreen listener
stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullscreen, false, 0, true);
// add event listeners to all buttons
mcVideoControls.btnPause.addEventListener(MouseEvent.CLICK, pauseClicked, false, 0, true);
mcVideoControls.btnPlay.addEventListener(MouseEvent.CLICK, playClicked, false, 0, true);
mcVideoControls.btnFullscreenOn.addEventListener(MouseEvent.CLICK, fullscreenOnClicked, false, 0, true);
mcVideoControls.btnFullscreenOff.addEventListener(MouseEvent.CLICK, fullscreenOffClicked, false, 0, true);
mcVideoControls.btnProgressBar.addEventListener(MouseEvent.MOUSE_DOWN, progressScrubberClicked, false, 0, true);
mcVideoControls.mcProgressScrubber.btnProgressScrubber.addEventListener(MouseEvent.MOUSE_DOWN, progressScrubberClicked, false, 0, true);
// create timer for updating all visual parts of player and add
// event listener
tmrDisplay = new Timer(DISPLAY_TIMER_UPDATE_DELAY);
tmrDisplay.addEventListener(TimerEvent.TIMER, updateDisplay, false, 0, true);
// create a new net connection, add event listener and connect
// to null because we don't have a media server
ncConnection = new NetConnection();
ncConnection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler, false, 0, true);
ncConnection.connect(null);
// create a new netstream with the net connection, add event
// listener, set client to this for handling meta data and
// set the buffer time to the value from the constant
nsStream = new NetStream(ncConnection);
nsStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler, false, 0, true);
nsStream.client = this;
nsStream.bufferTime = BUFFER_TIME;
// attach net stream to video object on the stage
vidDisplay.attachNetStream(nsStream);
// set the smoothing value from the constant
vidDisplay.smoothing = SMOOTHING;
// set default volume and get volume from shared object if available
var tmpVolume:Number = DEFAULT_VOLUME;
if(shoVideoPlayerSettings.data.playerVolume != undefined) {
tmpVolume = shoVideoPlayerSettings.data.playerVolume;
intLastVolume = tmpVolume;
}
// create new request for loading the playlist xml, add an event listener
// and load it
urlRequest = new URLRequest(strSource);
urlLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, playlistLoaded, false, 0, true);
urlLoader.load(urlRequest);
nsStream.play(strSource);
}
function playClicked(e:MouseEvent):void {
// check's, if the flv has already begun
// to download. if so, resume playback, else
// load the file
if(!bolLoaded) {
nsStream.play(strSource);
bolLoaded = true;
}
else{
nsStream.resume();
}
vidDisplay.visible = true;
// switch play/pause visibility
mcVideoControls.btnPause.visible = true;
mcVideoControls.btnPlay.visible = false;
}
function pauseClicked(e:MouseEvent):void {
// pause video
nsStream.pause();
// switch play/pause visibility
mcVideoControls.btnPause.visible = false;
mcVideoControls.btnPlay.visible = true;
}
function progressScrubberClicked(e:MouseEvent):void {
// set progress scrub flag to true
bolProgressScrub = true;
// start drag
mcVideoControls.mcProgressScrubber.startDrag(true, new Rectangle(0, 3.7, 432, 0)); // NOW TRUE
}
function mouseReleased(e:MouseEvent):void {
// set progress/volume scrub to false
bolVolumeScrub = false;
bolProgressScrub = false;
// stop all dragging actions
mcVideoControls.mcProgressScrubber.stopDrag();
// update progress/volume fill
mcVideoControls.mcProgressFill.mcFillRed.width = mcVideoControls.mcProgressScrubber.x + 5;
}
function updateDisplay(e:TimerEvent):void {
// checks, if user is scrubbing. if so, seek in the video
// if not, just update the position of the scrubber according
// to the current time
if(bolProgressScrub)
nsStream.seek(Math.round(mcVideoControls.mcProgressScrubber.x * objInfo.duration / 432))
else
mcVideoControls.mcProgressScrubber.x = nsStream.time * 432 / objInfo.duration;
// set time and duration label
mcVideoControls.lblTimeDuration.htmlText = "<font color='#ffffff'>" + formatTime(nsStream.time) + "</font> / " + formatTime(objInfo.duration);
// update the width from the progress bar. the grey one displays
// the loading progress
mcVideoControls.mcProgressFill.mcFillRed.width = mcVideoControls.mcProgressScrubber.x + 5;
mcVideoControls.mcProgressFill.mcFillGrey.width = nsStream.bytesLoaded * 438 / nsStream.bytesTotal;
// update volume and the red fill width when user is scrubbing
if(bolVolumeScrub) {
setVolume((mcVideoControls.mcVolumeScrubber.x - 318) / 53);
mcVideoControls.mcVolumeFill.mcFillRed.width = mcVideoControls.mcVolumeScrubber.x - 371 + 53;
}
// chech if user is currently hovering over description label
if(bolDescriptionHover) {
// check in which direction we're currently moving
if(bolDescriptionHoverForward) {
// move to the left and check if we've shown everthing
mcVideoControls.mcVideoDescription.lblDescription.x -= 0.1;
if(mcVideoControls.mcVideoDescription.lblDescription.textWidth - 133 <= Math.abs(mcVideoControls.mcVideoDescription.lblDescription.x))
bolDescriptionHoverForward = false;
} else {
// move to the right and check if we're back to normal
mcVideoControls.mcVideoDescription.lblDescription.x += 0.1;
if(mcVideoControls.mcVideoDescription.lblDescription.x >= 0)
bolDescriptionHoverForward = true;
}
} else {
// reset label position and direction variable
mcVideoControls.mcVideoDescription.lblDescription.x = 0;
bolDescriptionHoverForward = true;
}
}
function onMetaData(info:Object):void {
// stores meta data in a object
objInfo = info;
// now we can start the timer because
// we have all the neccesary data
if(!tmrDisplay.running)
tmrDisplay.start();
}
function netStatusHandler(event:NetStatusEvent):void {
// handles net status events
switch (event.info.code) {
// trace a messeage when the stream is not found
case "NetStream.Play.StreamNotFound":
trace("Stream not found: " + strSource);
break;
// when the video reaches its end, we check if there are
// more video left or stop the player
case "NetStream.Play.Stop":
//if(intActiveVid + 1 < xmlPlaylist..vid.length())
//playNext();
//else
nsStream.close();
removeChild(vidDisplay);
removeChild(mcVideoControls);
MovieClip(root).gotoAndPlay(2701);
stage.scaleMode = StageScaleMode.EXACT_FIT;
stage.displayState = StageDisplayState.NORMAL;
break;
}
}
function setVolume(intVolume:Number = 0):void {
// create soundtransform object with the volume from
// the parameter
var sndTransform = new SoundTransform(intVolume);
// assign object to netstream sound transform object
nsStream.soundTransform = sndTransform;
// hides/shows mute and unmute button according to the
// volume
if(intVolume > 0) {
mcVideoControls.btnMute.visible = true;
mcVideoControls.btnUnmute.visible = false;
} else {
mcVideoControls.btnMute.visible = false;
mcVideoControls.btnUnmute.visible = true;
}
// store the volume in the flash cookie
shoVideoPlayerSettings.data.playerVolume = intVolume;
shoVideoPlayerSettings.flush();
}
function formatTime(t:int):String {
// returns the minutes and seconds with leading zeros
// for example: 70 returns 01:10
var s:int = Math.round(t);
var m:int = 0;
if (s > 0) {
while (s > 59) {
m++; s -= 60;
}
return String((m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s);
} else {
return "00:00";
}
}
function fullscreenOnClicked(e:MouseEvent):void {
// go to fullscreen mode
stage.displayState = StageDisplayState.FULL_SCREEN;
}
function fullscreenOffClicked(e:MouseEvent):void {
// go to back to normal mode
stage.displayState = StageDisplayState.NORMAL;
}
function onFullscreen(e:FullScreenEvent):void {
// check if we're entering or leaving fullscreen mode
if (e.fullScreen) {
// switch fullscreen buttons
mcVideoControls.btnFullscreenOn.visible = false;
mcVideoControls.btnFullscreenOff.visible = true;
// size up video display
MovieClip(root).PlayerFrame.height = stage.height;
MovieClip(root).PlayerFrame.width = stage.width;
MovieClip(root).PlayerFrame.x = 0;
MovieClip(root).PlayerFrame.y = 0;
// bottom center align controls
} else {
// switch fullscreen buttons
mcVideoControls.btnFullscreenOn.visible = true;
mcVideoControls.btnFullscreenOff.visible = false;
MovieClip(root).PlayerFrame.x = 603;
MovieClip(root).PlayerFrame.y = 204;
MovieClip(root).PlayerFrame.width = 1020;
MovieClip(root).PlayerFrame.height = 614;
}
}
function playlistLoaded(e:Event):void {
// create new xml with loaded data from loader
xmlPlaylist = new XML(urlLoader.data);
// set source of the first video but don't play it
playVid(0, true)
// show controls
mcVideoControls.visible = true;
}
function playVid(intVid:int = 0, bolPlay = true):void {
if(bolPlay) {
// stop timer
tmrDisplay.stop();
// play requested video
nsStream.play(String(xmlPlaylist..vid[intVid].#src));
// switch button visibility
mcVideoControls.btnPause.visible = true;
mcVideoControls.btnPlay.visible = false;
} else {
strSource = xmlPlaylist..vid[intVid].#src;
}
// show video display
vidDisplay.visible = true;
// reset description label position and assign new description
mcVideoControls.mcVideoDescription.lblDescription.x = 0;
mcVideoControls.mcVideoDescription.lblDescription.htmlText = "<font color='#ffffff'>" + String(xmlPlaylist..vid[intVid].#desc) + "</font>";
// update active video number
intActiveVid = intVid;
}
// ###############################
// ############# INIT PLAYER
// ###############################
initVideoPlayer();
and the xml file consists of:
<?xml version="1.0" encoding="UTF-8"?>
<videolist>
<vid src="video/Intro.mp4" desc="Intro"/>
</videolist>
Please help.

Related

dispatch change value and start tween

I try to make simple scorebug. It’s feed from external XML file.
I want to start an animation when score changing, but i doesn’t found event listener or dispatcher to get change of value.
var myTimer:Timer = new Timer(100);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
myTimer.start();
function timerListener (e:TimerEvent):void
{
var myXMLLoader:URLLoader = new URLLoader();
myXMLLoader.load(new URLRequest("Xml.xml"));
myXMLLoader.addEventListener(Event.COMPLETE, processXML);
function processXML (e:Event):void
{
var myXML:XML = new XML(e.target.data);
ShotClock.text = myXML.timestamp;
GameClock.text = myXML.Clock;
HS.HomeScore.text = myXML.HomeScore;
AS.AwayScore.text = myXML.AwayScore;
Period.text = myXML.Period;
AwayTeam.text = myXML.AwayName;
HomeTeam.text = myXML.HomeName;
}
if ( (myXML.HomeScore).CHANGE )
{ var myTween:Tween = new Tween(HS.HomeScore, "alpha", Strong.easeIn, 0, 1, 1, true); }
}
You need to change the logic of loading. Instead of starting timed loadings, which won't be accurate 100 ms anyway, could lag, could fail, could arrive in order other than you issued them, etc., you need a single-thread asynchronous loop that does, simply, the following:
Start data loading.
(async pause)
Handle the loaded data.
Get XML data from loaded text.
Parse XML attributes.
Check if the score variable changed and trigger the things you want to.
Wait 100 ms.
(async pause)
Go to step №1.
Something like that:
var theLoader:URLLoader;
var theScore:Number = 0;
var theTimer:Timer;
// Start the tracking routine.
trackNext();
function trackNext():void
{
theLoader = new URLLoader;
theLoader.addEventListener(Event.COMPLETE, onXML);
// Error tracking is a must or the logic flow
// might just stop when you least expect it to.
theLoader.addEventListener(IOErrorEvent.IO_ERROR, onError, false, 0, true);
theLoader.load(new URLRequest("xml.xml"));
}
function onXML(e:Event):void
{
// Sanity check. There should be only one valid URLLoader instance.
if (e.target != theLoader)
{
return;
}
var X:XML;
try
{
X = new XML(theLoader.data);
}
catch (fail:Error)
{
// Processing the case where data is loaded successfully,
// but it is not a valid XML String.
onError(e);
return;
}
// Here's the place for your code
// that extracts data from XML.
// ...
// Get the new score value.
var aScore:Number = X.HomeScore;
// Compare it to previous value.
if (aScore != theScore)
{
// ATTENTION!!! THIS IS THE PLACE YOU ARE LOOKING FOR!!!
// Trigger things if the new score is any different.
// ...
// Keep the new score value.
theScore = aScore;
}
finishLoading();
}
// This method just ignores an error, think of it
// as of blank to process the exceptional cases.
function onError(e:Event):void
{
// Sanity check. There should be only one valid URLLoader instance.
if (e.target != theLoader)
{
return;
}
finishLoading();
}
// Call it finishLoading(true) to stop the tracking routine.
function finishLoading(thenstop:Boolean = false):void
{
// Dispose of the URLLoader instance if any.
if (theLoader)
{
var aLoader:URLLoader = theLoader;
theLoader = null;
aLoader.removeEventListener(Event.COMPLETE, onXML);
try
{
aLoader.close();
}
catch (fail:Error)
{
// Do nothing about it.
}
}
finishTimer();
if (thenstop)
{
return;
}
// Wait 100 ms to give Flash Player a breather
// before starting to load the file once more.
theTimer = new Timer(100, 1);
theTimer.addEventListener(TimerEvent.TIMER, onTime);
theTimer.start();
}
function finishTimer():void
{
// Dispose of the Timer instance if any.
if (theTimer)
{
theTimer.removeEventListener(TimerEvent.TIMER, onTime);
theTimer.stop();
theTimer = null;
}
}
function onTime(e:TimerEvent):void
{
// Now go for the next iteration.
finishTimer();
trackNext();
}

Added child stays invisible even though its container is visible

I have been struggling for a couple of days with an issue in Flash CS4. I am re-structuring an old game project into a Main class which handles the mainMenu, playGame, etc. functions. I have a ship added from the "game", which is added by Main.
The issue is "myShip" works as expected, except it's never visible. I've checked a lot of times, and both myShip and its containter (game) visible properties are always true. Alpha values are not the problem either, nor layers nor depth. Every other child I've added from "game" works just fine, but "myShip" refuses to be visible.
Any ideas as to why this could happen? I do not know how what to try next to solve the problem. Any help would be very appreciated. The code for the Main, Game and Ship class is below.
Thank you!
Code from the Main class:
public class Main extends Sprite {
public var mainMenuDisplay:MainMenuDisplay;
public var game:Game;
public var gameOverMenu:GameOverMenu;
public function Main() {
showMainMenu();
}
public function showMainMenu() {
mainMenuDisplay = new MainMenuDisplay(this);
gameOverMenu=remove_movie_clip(gameOverMenu);
addChild(mainMenuDisplay);
}
public function showGameOver() {
gameOverMenu = new GameOverMenu(this);
game=remove_movie_clip(game);
addChild(gameOverMenu);
}
public function playTheGame() {
game = new Game(this);
mainMenuDisplay = remove_movie_clip(mainMenuDisplay);
gameOverMenu=remove_movie_clip(gameOverMenu);
stage.addChild(game);
}
private function remove_movie_clip(clip:*) {
if (clip) {
removeChild(clip);
}
return null;
}
}
Code from the Game class:
package {
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import com.coreyoneil.collision.CollisionList;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.events.MouseEvent;
import com.greensock.*;
import flash.display.Sprite;
import flash.display.SpreadMethod;
import flash.display.GradientType;
import flash.geom.Matrix;
import com.sounds.music.Music_mainMusic;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.DisplayObject;
public class Game extends MovieClip {
var mainClass:Main;
//Main menu
//var mainMenuDisplay:MainMenuDisplay = new MainMenuDisplay();
//static var inMenu:Boolean = true;
//
//Ship variables
static var myShip:Ship = new Ship();
var myDirectionBar:Direction_bar = new Direction_bar();
//
//Enemy variables
static var enemyShipTimer_1:Timer;
//
//PowerUp variables
static var powerUpTimer:Timer;
static var nuking:Boolean;
//
//Wall generation variables
static var wall_mov_speed:Number;
var randomize:Number = 1;
var wallArray:Array = new Array();
var index:int = 0;
//
//Wall collision variables (powered by CDK by Corey O'Neil)
var myWallCollisionList:CollisionList; // = new CollisionList(myShip);
var wall_collisions:Array = new Array();
//
//Score variables
static var score:Number;
static var scoreText:TextField = new TextField();
var scoreFormat = new TextFormat("LCD5x8H", 20, 0x0066FF, true);
var distance_score_counter:int;
//
//Health variables
static var healthMeter_1:HealthMeter = new HealthMeter();
//
//Game modes
//var levelSelectDisplay:LevelSelectDisplay = new LevelSelectDisplay();
//**NOTE: These are extremely important, because they are the functions, which in reality are attributes, that allow us to call,
//from an Event Listener, a function in which we have a parameter to pass. This way we call these variables instead of the
//function we are interested in, these will call it for us.
//var functionLevelSelect_1:Function = selectedLevel(1);
//var functionLevelSelect_2:Function = selectedLevel(2);
//var functionLevelSelect_3:Function = selectedLevel(3);
//var functionLevelSelect_4:Function = selectedLevel(4);
//var functionLevelSelect_5:Function = selectedLevel(5);
//The level composition (that's the numbers of the frame in the MC of the Walls, each number is a type. The last one stores all of them.
//var level_1_composition:Array = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
//var level_2_composition:Array = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
//var level_3_composition:Array = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
//var level_4_composition:Array = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
//var storyModeLevelCompositions:Array = new Array(level_1_composition, level_2_composition, level_3_composition, level_4_composition);
//
var levelPlaying:int = 0;
var wallPieceCount:int = 0;
//
//Pause variables
var pauseScreen:PauseScreen = new PauseScreen();
//This variables states whether we are in pause or not
static var isPause:Boolean = false;
//This other tells us if we can pause at the moment or not
static var isPauseable:Boolean = false;
//
//Game Over, new Game and Game menu variables
//static var gameOverMenu:GameOverMenu = new GameOverMenu();
static var inGameStopping:Boolean = false;
//
//Transition screen variables
var darkening:Boolean;
//NOTE: We do it this way because, when putting an Enter Frame event listener onto the function funcTransition,
//which has a pass variable, the variable changed all the time to true, giving us problems.
//Background graphics variables
var color1:uint = Math.floor(Math.random()*0xFFFFFF + 1);
var color2:uint = Math.floor(Math.random()*0xFFFFFF + 1);
var colors:Object = {left:color1, right:color2};
var newColor1:uint = Math.floor(Math.random()*0xFFFFFF + 1);
var newColor2:uint = Math.floor(Math.random()*0xFFFFFF + 1);
var newColors:Object = {left:newColor1, right:newColor2};
var mySprite:Sprite = new Sprite();
//
//Music variables
var myMainMusic:Music_mainMusic = new Music_mainMusic();
//
//Credits variables
//var myCredits:Credits = new Credits();
//var myVersion:VersionDisplay = new VersionDisplay();
//
//Other variables
//var initThingy:Boolean;
var initTransition:Boolean = true;
var allPurposeCounter:int = 0;
var myTransitionScreen:TransitionScreen = new TransitionScreen();
//
//New necessary variables
//
public function Game(passedClass:Main) {
mainClass = passedClass;
if (stage) {
init(null);
}else{
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
}
public function init(e:Event) {
this.removeEventListener(Event.ADDED_TO_STAGE, init);
this.parent.addChild(this);
//Necessary initial booting:
mySprite.x = 0;
mySprite.y = 0;
stage.addChildAt(mySprite, 1);
drawGradient();
animateBackground();
//////////////////////////////////////////////////////
/*mainMenuDisplay.x = 400 - mainMenuDisplay.width/2;
mainMenuDisplay.y = 240 - mainMenuDisplay.height/2;
stage.addChild(mainMenuDisplay);*/
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/*levelSelectDisplay.x = 400 - levelSelectDisplay.width/2;
levelSelectDisplay.y = 240 - levelSelectDisplay.height/2;
levelSelectDisplay.visible = false;
stage.addChild(levelSelectDisplay);*/
//////////////////////////////////////////////////////
//Transitions
myTransitionScreen.visible = false;
stage.addChild(myTransitionScreen);
//
//////////////////////////////////////////////////////
//myCredits.x = 20;
//myCredits.y = 438;
//stage.addChild(myCredits);
//myVersion.x = 710;
//myVersion.y = 438;
//stage.addChild(myVersion);
//////////////////////////////////////////////////////
//myMainMusic.play(0,99999);
initGame(null);
//mainMenuIdleState();
//
}
//////////////////////////////////////////////////////
/*function mainMenuIdleState(){
stage.addChild(mainMenuDisplay);
stage.addChild(levelSelectDisplay);
inMenu = true;
mainMenuDisplay.visible = true;
mainMenuDisplay.mainMenuPlayStoryButton_instance.addEventListener(MouseEvent.MOUSE_DOWN, level_select);
mainMenuDisplay.mainMenuPlayEndlessButton_instance.addEventListener(MouseEvent.MOUSE_DOWN, endless_mode_selected);
}*/
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/*function endless_mode_selected(e:Event){
levelPlaying = 0;
initGame(null);
}*/
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/*function level_select(e:Event){
mainMenuDisplay.visible = false;
levelSelectDisplay.visible = true;
levelSelectDisplay.levelSelectButton1_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_1);
levelSelectDisplay.levelSelectButton2_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_2);
levelSelectDisplay.levelSelectButton3_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_3);
levelSelectDisplay.levelSelectButton4_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_4);
levelSelectDisplay.levelSelectButtonBack_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_5);
}
function selectedLevel(level:int):Function {
switch (level){
case 1:
return function(e:MouseEvent):void {
//trace("1 clicked");
levelPlaying = 1;
levelSelectDisplay.visible = false;
initGame(null);
}
break;
case 2:
return function(e:MouseEvent):void {
//trace("2 clicked");
levelPlaying = 2;
levelSelectDisplay.visible = false;
initGame(null);
}
break;
case 3:
return function(e:MouseEvent):void {
//trace("3 clicked");
levelPlaying = 3;
levelSelectDisplay.visible = false;
initGame(null);
}
break;
case 4:
return function(e:MouseEvent):void {
//trace("4 clicked");
levelPlaying = 4;
levelSelectDisplay.visible = false;
initGame(null);
}
break;
default:
return function(e:MouseEvent):void {
//trace("back clicked");
levelPlaying = 0;
levelSelectDisplay.visible = false;
mainMenuDisplay.visible = true;
levelSelectDisplay.levelSelectButton1_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_1);
levelSelectDisplay.levelSelectButton2_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_2);
levelSelectDisplay.levelSelectButton3_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_3);
levelSelectDisplay.levelSelectButton4_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_4);
levelSelectDisplay.levelSelectButtonBack_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_5);
}
break;
}
}*/
//////////////////////////////////////////////////////
function initGame(e:Event):void{
//This has so many redundancies, when everything is done, START CLEANING THIS!
//////////////////////////////////////////////////////
//Main menu
//mainMenuDisplay.visible = false;
//inMenu = false; THIS GOES AT THE END TO PREVENT PROBLEMS
//directNewGame tells us if we come from the newGame function (and thus we do not go through the mainMenuIdleState
//function and this instances have not been placed on stage) or not. If we come from the main menu, we DO need to
//remove them.
//
trace(myShip);
//Ship
myShip.x = -10; //Before there were numbers to implement stage.stageWidth/2;
myShip.y = 200; //Before there were numbers to implement stage.stageHeight/2;
myShip.visible = true;
//mainClass.addChild(myShip);
this.addChild(myShip);
//We make sure the ship doesn't enter to stage with 0 health
//(problems of working with only one instance of ship due to the static var references)
Ship.health = 100;
//Check "NOTE" below
myShip.alpha = 0.35;
myShip.visible = true;
//
trace(myShip.visible);
//Direction bar
myDirectionBar.x = stage.stageWidth/2;
myDirectionBar.y = stage.stageHeight/2;
this.addChild(myDirectionBar);
//
//Timers (enemies)
enemyShipTimer_1 = new Timer(1000)
enemyShipTimer_1.addEventListener(TimerEvent.TIMER, spawn_enemies);
enemyShipTimer_1.start();
//
//Timer (powerUps)
powerUpTimer = new Timer(10000);
powerUpTimer.addEventListener(TimerEvent.TIMER, spawn_powerUp);
powerUpTimer.start();
//
//PowerUps (other)
nuking = false;
//
myWallCollisionList = new CollisionList(myShip);
//Initial movement speed of the walls
wall_mov_speed = 8;
//Calling to the generating/adequating wallArray function
adequateArrayOfWalls(true);
wallArray[0].gotoAndStop(1);
wallArray[1].gotoAndStop(1);
myWallCollisionList.addItem(wallArray[0].theActualWall);
myWallCollisionList.addItem(wallArray[1].theActualWall);
//Collision managements
wall_collisions = 0 as Array;
//NOTE: Here we limit the alpha value to consider for collision just to make sure the game doesn't start with you killed, and that you are "invincible"
//for some time
myWallCollisionList.alphaThreshold = 0.95;
//
//Adding score format and text
scoreText.defaultTextFormat = scoreFormat;
scoreText.x = 700;
scoreText.y = 10;
score = 0;
scoreText.text = String(score);
stage.addChild(scoreText);
distance_score_counter = 0;
scoreText.visible = true;
//
//Adding health meter
healthMeter_1 = new HealthMeter();
healthMeter_1.x = 10;
healthMeter_1.y = 10;
stage.addChild(healthMeter_1);
//
//Adding the Pause screen & other pause variables
pauseScreen.x = 400 - pauseScreen.width/2;
pauseScreen.y = 240 - pauseScreen.height/2;
pauseScreen.visible = false;
stage.addChild(pauseScreen);
isPauseable = true;
//Adding a key managing event (for pausing, menu, etc.)
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyManaging);
//
/*//Adding a Game Over Menu
gameOverMenu = new GameOverMenu();
gameOverMenu.x = 400 - gameOverMenu.width/2;
gameOverMenu.y = 240 - gameOverMenu.height/2;
gameOverMenu.visible = false;
stage.addChild(gameOverMenu);
gameOverMenu.playAgainButton_instance.addEventListener(MouseEvent.MOUSE_DOWN, newGame);
gameOverMenu.backToMenuButton_instance.addEventListener(MouseEvent.MOUSE_DOWN, backToTheMenu);
//*/
//Shield
//
//Event listeners
addEventListener(Event.ENTER_FRAME, update_game);
//
//////////////////////////////////////////////////////
/*//Credits
myCredits.visible = false;
myVersion.visible = false;
//
initThingy = true;
inMenu = false;*/
//////////////////////////////////////////////////////
}
function update_game(e:Event){
myShip.visible = true;
//Look the adequate array function for more info. We are just moving the two pieces of the array on stage
wallArray[(index - 1)].x -= wall_mov_speed;
wallArray[index].x -= wall_mov_speed;
if(wallArray[index].x < 0){
spawn_wall_piece();
}
//
if(index == 5){
//We call this function for cleaning
adequateArrayOfWalls(false);
}
if(wall_mov_speed < 20){
wall_mov_speed += 0.003;
}
wall_collisions = myWallCollisionList.checkCollisions();
if(wall_collisions.length > 0){
trace("hit!");
if(myShip.visible == true){
//We only kill the ship if it's visible, if not, it means it is already dead
Ship.receiveDamage(Ship.max_health);
}
wall_collisions = 0 as Array;
}
if(distance_score_counter >= 10){
distance_score_counter = 0;
updateScore(1);
}
distance_score_counter++;
//NOTE2: We use this nuke variable in order not to make the "nuke()" function static, type in which we couldn't handle the stage property
//And we also make this variable false here so as to eliminate not only a single enemy but all on stage
Enemy1.enemies_1Nuked = false;
if(nuking == true){
Enemy1.enemies_1Nuked = true;
nuking = false;
}
//We put these all the time at the front so we can see them and the walls don't overpass them
scoreText.parent.setChildIndex(scoreText, scoreText.parent.numChildren - 1);
healthMeter_1.parent.setChildIndex(healthMeter_1, healthMeter_1.parent.numChildren - 1);
pauseScreen.parent.setChildIndex(pauseScreen, pauseScreen.parent.numChildren -1);
//gameOverMenu.parent.setChildIndex(gameOverMenu, gameOverMenu.parent.numChildren - 1);
var n:uint = stage.numChildren;
for(var i=0; i < n; i++){
if(stage.getChildAt(i) is Enemy1){
var anEnemy1:Enemy1 = Enemy1(stage.getChildAt(i));
anEnemy1.parent.setChildIndex(anEnemy1, anEnemy1.parent.numChildren -1);
}
else if(stage.getChildAt(i) is PowerUp){
var aPowerUp:PowerUp = PowerUp(stage.getChildAt(i));
aPowerUp.parent.setChildIndex(aPowerUp, aPowerUp.parent.numChildren -1);
}
}
//Done like this due to the impossibility of calling a function inside an static one (in this case, gameOver)
if(inGameStopping == true){
funcEasing();
}
//Probably not necessary later
//////////////////////////////////////////////////////
/*if(initThingy == true){
stage.focus = stage;
initThingy = false;
}*/
//////////////////////////////////////////////////////
}
function spawn_enemies(e:Event){
var myEnemy1:Enemy1 = new Enemy1();
stage.addChild(myEnemy1);
}
function spawn_wall_piece(){
index++;
wallArray[index].x = (wallArray[index - 1].x + wallArray[index - 1].width);
wallArray[index].y = 0;
stage.addChild(wallArray[index]);
myWallCollisionList.addItem(wallArray[index].theActualWall);
myWallCollisionList.removeItem(wallArray[index - 2].theActualWall);
stage.removeChild(wallArray[index - 2]);
}
function adequateArrayOfWalls(init:Boolean):void{
//This only executes if we are initialitizing the array
if(init == true){
for(index = 0; index < 10; index++){
var aWall:Walls = new Walls();
//We check if we got special blocks next (e.g. "ramp caves"). Then we only allow a certain type of blocks to come.
//If no special block is detected, then we just randomize the next one, except for those that are not allowed to
//show up unless a previous special one appeared.
if(randomize == 9 || randomize == 15){
randomize = 15 + Math.floor(Math.random()*1 + 1);
}else{
randomize = Math.floor(Math.random()*14 + 1);
}
aWall.gotoAndStop(randomize);
//TheActualWall is the raw shape of the wall, where the ship collides, and it is what we push into collisionList,
//but not into the wallArray which includes the Walls (comprised by graphics and actual walls)
aWall.theActualWall.gotoAndStop(randomize);
wallArray.push(aWall);
}
wallArray[0].gotoAndStop(1);
wallArray[0].theActualWall.gotoAndStop(1);
stage.addChild(wallArray[0]);
wallArray[1].x = 800;
wallArray[1].y = 0;
stage.addChild(wallArray[1]);
//if not, then we are just cleaning it and rearranging it so it doesn't grow bigger and bigger
}else{
for(var a:Number = 0; a < index - 1; a++){
wallArray.splice(0,1);
}
for(a = index - 1; a < (10-2); a++){
var aWall2:Walls = new Walls();
if(randomize == 9 || randomize == 15){
randomize = 15 + Math.floor(Math.random()*1 + 1);
}else{
randomize = Math.floor(Math.random()*14 + 1);
}
aWall2.gotoAndStop(randomize);
aWall2.theActualWall.gotoAndStop(randomize);
wallArray.push(aWall2);
}
}
//Then, either way, we tell index to be 1 since the reference in the function is [index - 1] and [index], so it starts with [0] and [1]
index = 1;
}
static function updateScore(points:Number){
score += points;
scoreText.text = score.toString();
}
static function resetScore(){
score = 0;
scoreText.text = score.toString();
}
function spawn_powerUp(e:Event){
var pU:PowerUp = new PowerUp();
stage.addChild(pU);
}
static function gameOver(){
wall_mov_speed = 8;
//gameOverMenu.end_game_score_display.text = score.toString();
//gameOverMenu.visible = true;
scoreText.visible = false;
enemyShipTimer_1.stop();
powerUpTimer.stop();
inGameStopping = true; //In game stopping only influentiates in the easing speed effect
isPauseable = false;
}
function funcEasing(){
if(wall_mov_speed >= 0.1){
wall_mov_speed /= 1.07;
}else{
wall_mov_speed = 0;
removeEventListener(Event.ENTER_FRAME, update_game);
initTransition = true;
darkening = true; //See notes on variable declaration.
funcTransition(null);
}
}
function funcTransition(e:Event){
if(initTransition == true){
myTransitionScreen.init(darkening);
myTransitionScreen.parent.setChildIndex(myTransitionScreen, stage.numChildren - 1);
myTransitionScreen.parent.addEventListener(Event.ENTER_FRAME, funcTransition);
initTransition = false;
allPurposeCounter = 0;
}
if((darkening == true && myTransitionScreen.alpha == 1) || (darkening == false && myTransitionScreen.alpha == 0)){
trace("fsdfa");
allPurposeCounter++;
trace(allPurposeCounter);
if(allPurposeCounter >= 20){
myTransitionScreen.parent.removeEventListener(Event.ENTER_FRAME, funcTransition);
initTransition = true;
allPurposeCounter = 0;
if(darkening == true){ //This means if we are now with a black screen coming from the game, which is when we will end our game process
endGameProcess();
}
}
}
}
function endGameProcess(){
mainClass.showGameOver();
}
function newGame(e:Event){
darkening = true; //See notes on variable declaration.
initTransition = true;
funcTransition(null);
}
//Check To-Do List below
function funcPause(pMode:String){
if(pMode == "pausing"){
pauseScreen.visible = true;
removeEventListener(Event.ENTER_FRAME, update_game);
myShip.thePause("pausing");
//Check and stop the childs on stage (emitted by stage, so particles don't count)
var n:uint = stage.numChildren;
for(var i=0; i < n; i++){
if(stage.getChildAt(i) is Enemy1){
var anEnemy1:Enemy1 = Enemy1(stage.getChildAt(i));
anEnemy1.thePause("pausing");
}
else if(stage.getChildAt(i) is Trail){
var aTrailUnit:Trail = Trail(stage.getChildAt(i));
aTrailUnit.thePause("pausing");
}
else if(stage.getChildAt(i) is PowerUp){
var aPowerUp:PowerUp = PowerUp(stage.getChildAt(i));
aPowerUp.thePause("pausing");
}
}
enemyShipTimer_1.stop();
powerUpTimer.stop();
isPause = true;
isPauseable = false;
}else if(pMode == "unpausing"){
pauseScreen.visible = false;
addEventListener(Event.ENTER_FRAME, update_game);
myShip.thePause("unpausing");
//Check and re-run the childs on stage (emitted by stage, so particles don't count)
var m:uint = stage.numChildren;
for(var j=0; j < m; j++){
if(stage.getChildAt(j) is Enemy1){
var anotherEnemy1:Enemy1 = Enemy1(stage.getChildAt(j));
anotherEnemy1.thePause("unpausing");
}
else if(stage.getChildAt(j) is Trail){
var anotherTrailUnit:Trail = Trail(stage.getChildAt(j));
anotherTrailUnit.thePause("unpausing");
}
else if(stage.getChildAt(j) is PowerUp){
var anotherPowerUp:PowerUp = PowerUp(stage.getChildAt(j));
anotherPowerUp.thePause("unpausing");
}
}
enemyShipTimer_1.start();
powerUpTimer.start();
isPause = false;
isPauseable = true;
}
}
//Key pressing management
function keyManaging(e:KeyboardEvent){
var key:uint = e.keyCode;
trace("algo");
switch (key){
case Keyboard.P:
if(isPause == false && isPauseable == true){
funcPause("pausing");
}else if (isPause == true){
funcPause("unpausing");
}
break;
case Keyboard.M:
//go back to menu: still to complete
//Has to be only possible to do while in the pause menu
trace("going back to menu");
//
break;
}
}
//
//Background color management
function drawGradient():void {
var m:Matrix = new Matrix();
m.createGradientBox(805, 485, 0, 0, 0);
mySprite.graphics.clear(); // here we clean it
mySprite.graphics.beginGradientFill(GradientType.LINEAR, [colors.left, colors.right], [1, 1], [0x00, 0xFF], m, SpreadMethod.REFLECT);
mySprite.graphics.drawRoundRect(0,0,805,485, 0);
stage.setChildIndex(mySprite, 1);
}
function animateBackground(){
TweenMax.to(colors, 3, {hexColors:{left:newColor1, right:newColor2}, onUpdate:drawGradient, onComplete:reRandomize});
}
function reRandomize(){
color1 = newColor1;
color2 = newColor2;
newColor1 = Math.floor(Math.random()*0xFFFFFF + 1);
newColor2 = Math.floor(Math.random()*0xFFFFFF + 1);
animateBackground();
}
}
}
Code from Ship:
public class Ship extends MovieClip {
public function Ship() {
if (stage) {
init(null);
}else{
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
}
public function init(e:Event) {
this.removeEventListener(Event.ADDED_TO_STAGE, init);
this.addEventListener(Event.ENTER_FRAME, update_ship);
}
public function update_ship(e:Event){
x_vel = Direction_bar.dX*power;
y_vel = Direction_bar.dY*power;
this.x += x_vel;
this.y += y_vel;
if((10 < Math.abs(Direction_bar.dX) || 10 < Math.abs(Direction_bar.dY)) || ((0.9 < Math.abs(x_vel)||(0.9 < Math.abs(y_vel))))){
this.rotation = Direction_bar.point_direction;
}
rotation_now = this.rotation;
if(myShield != null){
if(myShield.visible == true){
myShield.alpha -= 0.0005;
if(myShield.alpha == 0){
myShield.visible = false;
myShield.alpha = 1;
}
}
}
}
Some basics that you have to know in order to understand what's going on.
It's a very common mistake to add things to stage.
Here's what the documentation of addChild says
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html#addChild%28%29
objects should not be added to the Stage, directly, at all
I guess people add DispalyObjects to stage because they think it is
"the stage" that they see and interact with in the Flash authoring
environment. But it's not. stage.addChild() is not the same
thing as dragging a symbol from the library onto the screen. What by
default represents the main time line is the root property.
However, if you add anything to stage directly, its root property and its stage property both reference the same object,
which is regularly only referenced by stage. stage is some
container that your .swf is added to when running in the flash
player.
The documentation of addChildAt says this about the index:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html#addChildAt%28%29
The child is added at the index position specified. An index of 0 represents the back (bottom) of the display list for this
DisplayObjectContainer object.
Applying these basics, the following happens:
FlashPlayer creates the stage object, instantiates your main class
and adds that instance to stage, it is the child with the index 0.
Among other things, stage.addChildAt(mySprite, 1); is executed,
adding mySprite as a second child to stage. With index of 1 it is
rendered in front of the object that is at index 0, which happens to
be the instance of your main class AKA your .swf file. I hope that
anything being rendered "outside the .swf file" illustrates well
enough why adding things to stage is not recommended.
Later, this.addChild(myShip); happens. (Which is actually the
proper way to do it; no need to use this here:addChild(myShip);
is all you need.) and adds the ship to the display list. Assuming all
of its parents are added to the display list as well, it will be
displayed.
But you still cannot see it, because you added mySprite in front of
the instance of your main class and filled it with a content in
drawGradient() which covers up everything else.
In all honesty, the best solution would be to start over from scratch.
Working with this code will not help you in any way. Even working yourself through it and making it work somehow will not make you understand anything better (except for how not to do things). It seems like the only motivation to modify this code to use classes was for the sake of doing it. Forcing such old code into the object oriented paradigm will not work very well. The benefits of oop will not be apparent, making this experience even more frustrating.
Last but not least, do not roll your own transition code. There are many libraries that do this (including flash's own Tween class http://www.republicofcode.com/tutorials/flash/as3tweenclass/ or the popular tweenlite http://greensock.com/tweenlite)
You could try adding an ADDED_TO_STAGE event. See this excellent explanation from the master of game programming
Understanding ADDED_TO_STAGE Event

Using the Feathers ScreenNavigator with Starling and Signals

I'm new to Flash, Starling, and Feathers and am giving myself a kind of crash course, but am getting confused. I simply want my root starling class to initiate my game screen. I apologize if this is noobish. I really do want to understand.
I am not sure what dispatches FeathersEventType.INITIALIZE and I'm having trouble dispatching it manually. Any pointers in the right direction would be greatly appreciated.
In my Main.as (my Document Class), I instantiate starling, wait for the Root to be created, and then call its Start function (saw this in an example of how to show an initial background, not sure if it's best practice).
this.mStarling = new Starling(Root, this.stage, viewPort);
... //set background from embed
mStarling.addEventListener(starling.events.Event.ROOT_CREATED,
function(event:Object, app:Root):void
{
mStarling.removeEventListener(starling.events.Event.ROOT_CREATED, arguments.callee);
removeChild(background);
background = null;
var bgTexture:Texture = Texture.fromEmbeddedAsset(
backgroundClass, false, false);
//app.start(bgTexture, assets);
app.start(bgTexture, assets) // call the START on my root class
mStarling.start();
});
Here's my Root class (which is the root class passed to Starling)
public function Root()
{
if (verbose) trace(this + "Root(" + arguments);
super();
this.addEventListener(FeathersEventType.INITIALIZE, initializeHandler);
}
// this is not being called
private function initializeHandler(e:Event):void
{
this._navigator.addScreen(GAME_SCREEN, new ScreenNavigatorItem(GameScreen,
{
complete: MAIN_MENU
}));
}
public function start(background:Texture, assets:AssetManager):void
{
sAssets = assets; // assets loaded on document class
addChild(new Image(background)); // passed from doc class
this._navigator = new ScreenNavigator();
this.addChild(this._navigator);
var progressBar:ProgressBar = new ProgressBar(300, 20);
progressBar.x = (background.width - progressBar.width) / 2;
progressBar.y = (background.height - progressBar.height) / 2;
progressBar.y = background.height * 0.85;
addChild(progressBar);
// Progress bar while assets load
assets.loadQueue(function onProgress(ratio:Number):void
{
progressBar.ratio = ratio;
if (ratio == 1)
Starling.juggler.delayCall(function():void
{
gameScreen = new GameScreen();
trace("got this far" + gameScreen);
gameScreen.GAME_OVER.add(gotoGameOverScreen);
gameOverScreen = new GameOverScreen();
gameOverScreen.PLAY_AGAIN.add(gotoGameScreen);
progressBar.removeFromParent(true);
// This is where I'd like the GAME_SCREEN to show.
// now would be a good time for a clean-up
System.pauseForGCIfCollectionImminent(0);
System.gc();
}, 0.15);
});
This is part of my Root Class
public function start(background:Texture, assets:AssetManager):void
{
stageW= int(stage.stageWidth);
stageH = int(stage.stageHeight);
sAssets = assets;
bgIma=new Image(background);
bgIma.height=g.stageH * 0.4;
bgIma.scaleX=bgIma.scaleY;
bgIma.x=(g.stageW-bgIma.width)>>1;
bgIma.y=(g.stageH-bgIma.height)>>1;
addChild(bgIma);
var progressBar:ProgressBar = new ProgressBar(175, 20);
progressBar.x = (g.stageW - progressBar.width) >> 1;
progressBar.y = (g.stageH - progressBar.height) >> 1;
progressBar.y = g.stageH * 0.8;
addChild(progressBar);
assets.loadQueue(function onProgress(ratio:Number):void
{
progressBar.ratio = ratio;
if (ratio == 1)
Starling.juggler.delayCall(function():void
{
progressBar.removeFromParent(true);
removeChild(bgIma);
bgIma=null;
addedToStageHandler();
addSounds();
System.pauseForGCIfCollectionImminent(0);
System.gc();
}, 0.15);
});
}
protected function addedToStageHandler(event:starling.events.Event=null):void
{
this._navigator = new ScreenNavigator();
_navigator.autoSizeMode = ScreenNavigator.AUTO_SIZE_MODE_CONTENT;
this.addChild( this._navigator );
this._transitionManager = new ScreenFadeTransitionManager(_navigator);
this._navigator.addScreen( "Fluocode", new ScreenNavigatorItem(Fluocode));
this._navigator.addScreen( "Main", new ScreenNavigatorItem(AppMain));
this._navigator.showScreen("Fluocode");
this._transitionManager.duration = 0.5;
this._transitionManager.ease = Transitions.EASE_IN;
}

Movie clips not on the scene automatically playing, when the scene loads

I'm developing an app for android using flash and adobe air for android.
In flash i have a set of Scenes which can be navigated in the following way.
in the lower scenes (morning, noon and evening scenes), i have one movie clip every 5 frames per scene, which have audio embedded in them. on the first frame of the movie clips i have, i call the stop(); function. and at the end of the clip an event is dispatched ( dispatchEvent(new Event ("MEANING_TEXT_COMPLETE")); ), so that code from the main timeline could act accordingly.
Here is the code on my main timeline
import flash.events.MouseEvent;
MovieClip(this.root).stop();
btn_home_parent.addEventListener(MouseEvent.CLICK, goto_dh_morn);
mc_sound.addEventListener(MouseEvent.CLICK, control_sound_morn);
btn_next_morn.addEventListener(MouseEvent.CLICK, goto_next_morn);
btn_prev_morn.addEventListener(MouseEvent.CLICK, goto_prev_morn);
//load all sound files
var mn_1:Mn1 = new Mn1();
var mn_2:Mn2 = new Mn2();
var mn_3:Mn3 = new Mn3();
var mn_4:Mn4 = new Mn4();
var mn_5:Mn5 = new Mn5();
var mn_6:Mn6 = new Mn6();
var mn_7:Mn7 = new Mn7();
var mn_8:Mn8 = new Mn8_();
var mn_9:Mn9 = new Mn9();
var mn_10:Mn10 = new Mn10();
var mn_11:Mn11 = new Mn11();
var mn_12:Mn12 = new Mn12();
var mn_13:Mn13 = new Mn13();
var mn_14:Mn14 = new Mn14();
var frameCount_morn:int = 1;
var lang1Init_morn:Boolean = false;
var lang1:Object;
var ar:Object;
playSound_morn();
function playSound_morn()
{
var currentSound:Sound = new Sound();
channel.stop();
trace("play sound");
currentSound = this["mn_" + frameCount_morn];
channel = currentSound.play();
channel.addEventListener(Event.SOUND_COMPLETE, soundComplete_morn);
trans.volume = 1;
channel.soundTransform = trans;
}
function soundComplete_morn(e:Event):void
{
if (showlang1Text)
{
trace("ar Sound Complete");
ar = getChildByName("arText" + (currentFrame - 1));
ar.visible = false;
trace("ar child acquired");
lang1 = getChildByName("lang1Text" + (currentFrame - 1));
lang1Init_morn = true;
lang1.visible = true;
lang1.play();
lang1.addEventListener("MEANING_TEXT_COMPLETE", translationComplete_morn);
}
}
function translationComplete_morn(e:Event)
{
trace("translate Complete");
ar= getChildByName("arText" + (currentFrame - 1));
ar.visible = true;
lang1 = getChildByName("lang1Text" + (currentFrame - 1));
lang1.visible = false;
}
function goto_next_morn(e:MouseEvent)
{
if (MovieClip(this.root).currentFrame <= 61)
{
var next_frame = MovieClip(this.root).currentFrame + 5;
frameCount_morn = frameCount_morn + 1;
channel.stop();
if (lang1Init_morn){lang1.stop();lang1Init_morn = false;}
MovieClip(this.root).gotoAndStop(next_frame);
playSound_morn();
}
trace("Current Frame: " + currentFrame);
}
function goto_prev_morn(e:MouseEvent)
{
if (MovieClip(this.root).currentFrame > 0)
{
var prev_frame = MovieClip(this.root).currentFrame - 5;
frameCount_morn = frameCount_morn - 1;
channel.stop();
if (lang1Init_morn){lang1.stop();lang1Init_morn = false;}
MovieClip(this.root).gotoAndStop(prev_frame);
playSound_morn();
}
trace("Current Frame: " + currentFrame);
}
function control_sound_morn(e:MouseEvent)
{
control_sound(e);
if (!showlang1Text) {
mc_sound.gotoAndStop(5);
if (lang1Init_morn){
lang1.stop();
lang1Init_morn = false;
ar.visible = true;
lang1.visible = false;
}
}
else {
mc_sound.gotoAndStop(1)
}
}
function goto_dh_morn(e:MouseEvent) {
if (lang1Init_morn){lang1.stop();lang1Init_morn = false;}
channel.stop();
goto_dh(e);
}
the movie clip object is lang1
when i load the scene "Morning Scene" it works perfectly well, as it should. however when i navigate to the "noon scene" or "evening scene", audio from all the movie clips that were put on the "morning scene" automatically starts to play. The funny thing is that those movie clips are not even added to the "noon scene" and "evening scene". Any idea on why this happens or how to fix it.
thanks
as I got no answers. the way I fixed it was to compile each scene to a separate swf file and then load/unload them when needed.

Scrubbing grandchild’s timeline causes previously unloaded grandchild swf’s sound to play, interfering with sound of currently playing grandchild swf

what problem am I facing?
I have a parent file. It loads a child by name of overview file. Overview file further loads many (grandchild) files. I have a timeline scrubber on parent file. It scrubs both child as well as grandchild files. The problem is if I load a grandchild file, unload it. then load next grandchild file and scrub the timeline, the sound of previously loaded grandchild file starts playing. How can I stop it?? Please help, I have tried hard but I could not solve, I am amateur, no formal programming knowledge. Thanks.
I am providing a link http://www.sendspace.com/filegroup/RA9RziNuDlC2MPj%2F11DoLLkW4A7ota%2B4KmmbltoalaeH%2FYEipSU22U2tlMBOBefBFc1RnhYpLCv3pRyAfFLxfA in case someone wants to see code.
To reproduce error: Open parent file. click on armored link, then click on home button to unload it. Now, click on artillery link, drag the scrubber.
Now you will hear overlapping sound of the previously unloaded “armored” grandchild swf being played along with that artillery swf's sound.
//CUSTOM event sent by child swf, once grandchild swf is loaded
stage.addEventListener("playGrandchildScrubber", disableScrubberF);
function disableScrubberF(e:Event):void
{
var grandChildMC:MovieClip = thisMC.myLoader.content;
var actualTrackLengthGC : Number = ((scrubberMC.scrubBarMC.width) - (scrubberMC.scrubHandleMC.width));
var animLengthGC : int = grandChildMC.totalFrames;
var leftBoundGC : Number = scrubberMC.scrubBarMC.x;
var rightBoundGC : Number = scrubberMC.scrubBarMC.x + actualTrackLengthGC;
var dragBoundGC : Rectangle = new Rectangle(leftBoundGC, scrubberMC.scrubHandleMCGC.y, actualTrackLengthGC, 0);
var calcWidthGC : Number = actualTrackLength/grandChildMC.totalFrames;
//sets the value of boolean "grandChildSwfLoaded" to true, indicating gradchild swf has been loaded.
grandChildSwfLoaded = true;
//Hides scrubberhandle, totoal time and current time, fill of CHILD TIMELINE SCRUBBER. GRANDCHILD TIMELINE SCRUBBER HANDLE
//CURRENT TIME AND TOTOAL TIME BECOME VISIBLE.
currentTimeGC.visible= true;
totalTimeGC.visible=true;
totaltime.visible = false;
currentTime.visible = false;
scrubberMC.scrubHandleMCGC.visible = true;
scrubberMC.scrubHandleMC.visible = false;
scrubberMC.fill_mcGC.visible = true;
scrubberMC.fill_mc.visible = false;
//CODE FOR CURRENT TIME OF GRAND CHILD SWF
var totalSeconds = Math.floor(grandChildMC.totalFrames / 24);
var input = totalSeconds;
var totalAnimTime = (input > 3600 ? Math.floor(input/3600) + ':':'')
+(input%3600 < 600 ? '0':'')+Math.floor(input%3600/60)+':'
+(input%60 < 10 ? '0':'')+input%60;
totalTimeGC.text = " / " + totalAnimTime;
//thisMC refers to child swf, i.e., overview swf
thisMC.stop();
animationPlaying = false;
grandChildMC.play();
grandchildAnimationPlaying = true
scrubberMC.addEventListener(Event.ENTER_FRAME, updateScrubberGC);
scrubberMC.scrubHandleMCGC.x = leftBoundGC;
scrubberMC.scrubHandleMCGC.buttonMode = true;
scrubberMC.scrubHandleMCGC.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseEventsGC);
function handleMouseEventsGC(evt:MouseEvent):void
{
switch(String(evt.type)) {
//following work is done when you hold the mouse down.
case MouseEvent.MOUSE_DOWN:
removeEventListener(Event.ENTER_FRAME, playScrubGC);
scrubberMC.removeEventListener(Event.ENTER_FRAME, updateScrubberGC);
scrubberMC.scrubHandleMCGC.startDrag(false, dragBoundGC);
stage.addEventListener(MouseEvent.MOUSE_UP, handleMouseEventsGC);
grandChildMC.addEventListener(Event.ENTER_FRAME, scrubMovieGC);
if (grandchildAnimationPlaying) grandChildMC.stop();
break;
case MouseEvent.MOUSE_UP:
scrubberMC.scrubHandleMCGC.stopDrag();
stage.removeEventListener(MouseEvent.MOUSE_UP, handleMouseEventsGC);
grandChildMC.removeEventListener(Event.ENTER_FRAME, scrubMovieGC);
if (grandchildAnimationPlaying) grandChildMC.play();
grandchildAnimationPlaying = true;
scrubberMC.addEventListener(Event.ENTER_FRAME, updateScrubberGC);
pp.play_btn.visible = false;
pp.pause_btn.visible = true;
if (grandChildMC.currentLabel == "swfComplete") {
//disable pause button on last frame
disablePause_mc.visible=true;
} else {
//enable pause button on all frames except last frame
disablePause_mc.visible=false;
}
if (grandChildMC.currentFrame==grandChildMC.totalFrames) {
grandChildMC.stop();
}else{
grandChildMC.play();
}
if (grandChildMC.currentFrame > grandChildMC.totalFrames) {
scrubberMC.removeEventListener(Event.ENTER_FRAME, updateScrubberGC);
}
break;
}
}
function scrubMovieGC(evt:Event):void
{
scrubberMC.removeEventListener(Event.ENTER_FRAME, updateScrubberGC);
var scrubPosGC : int = scrubberMC.scrubHandleMCGC.x;
var calcWidthGC : Number = actualTrackLengthGC/grandChildMC.totalFrames;
var gotoFrameGC : int = Math.ceil(scrubPosGC /calcWidthGC);
thisMC.stop()
grandChildMC.gotoAndStop(gotoFrameGC);
}
function updateScrubberGC(evt:Event):void
{
var percentGC : Number = ((grandChildMC.currentFrame)/(grandChildMC.totalFrames));
scrubberMC.scrubHandleMCGC.x = percentGC * actualTrackLengthGC;
scrubberMC.fill_mcGC.width = percentGC * actualTrackLengthGC;
//CODE FOR CURRENT TIME OF GRAND CHILD SWF
var currentSeconds = Math.floor(grandChildMC.currentFrame/24);
var CurrentInput = currentSeconds;
var timeElapsed = (CurrentInput > 3600 ? Math.floor(CurrentInput/3600) + ':':'') //hours
+(CurrentInput%3600 < 600 ? '0':'')+Math.floor(CurrentInput%3600/60)+':' //minutes
+(CurrentInput%60 < 10 ? '0':'')+CurrentInput%60; //seconds
currentTimeGC.text = timeElapsed;
}
addEventListener(Event.ENTER_FRAME, playScrubGC);
function playScrubGC(event:Event):void{
var percentGC : Number = ((grandChildMC.currentFrame)/(grandChildMC.totalFrames));
var actualTrackLengthGC : Number = ((scrubberMC.scrubBarMC.width) - (scrubberMC.scrubHandleMCGC.width));
scrubberMC.scrubHandleMCGC.x = percentGC * actualTrackLengthGC;
scrubberMC.fill_mcGC.width = percentGC * actualTrackLengthGC;
var scrubPosGC : int = scrubberMC.scrubHandleMCGC.x;
var calcWidthGC : Number = actualTrackLengthGC/grandChildMC.totalFrames;
var gotoFrameGC : uint = Math.round(scrubPosGC/calcWidthGC);
//CODE FOR CURRENT TIME OF GRAND CHILD SWF
var currentSeconds = Math.floor(grandChildMC.currentFrame/24);
var CurrentInput = currentSeconds;
var timeElapsed = (CurrentInput > 3600 ? Math.floor(CurrentInput/3600) + ':':'') //hours
+(CurrentInput%3600 < 600 ? '0':'')+Math.floor(CurrentInput%3600/60)+':' //minutes
+(CurrentInput%60 < 10 ? '0':'')+CurrentInput%60; //seconds
currentTimeGC.text = timeElapsed;
}
}
stage.addEventListener("enableChildScrubberDisableGrandchildScrubber", enableScrubberF);
function enableScrubberF(e:Event):void
{
currentTimeGC.visible= false;
totalTimeGC.visible=false;
totaltime.visible = true;
currentTime.visible = true;
scrubberMC.scrubHandleMCGC.visible = false;
scrubberMC.scrubHandleMC.visible = true;
scrubberMC.fill_mcGC.visible = false;
scrubberMC.fill_mc.visible = true;
}