"is MovieClip" is true, yet compiler insists it is not and throws Error #1034: Type Coercion failed? (AS3) - actionscript-3

I have in my library, various food icons converted and linked as MovieClips which i add to the scene dynamically. I'm trying to move them from one container to another. Containers are also dynamically added MovieClips.
I've been trying to move these icons who are "MovieClip extended class" instances to another MovieClip as child, by drag and drop, yet currentTarget in drop(it is fine in drag) is not recognised as MovieClip even with "currentTarget as MovieClip" and compiler throws error. Every trace indicates that it is indeed a MovieClip though. I'm at my wits end.
The "plate.addChild(mc);" is causing the error during dropping into the "plate" from "shelves".
The .fla file: https://1drv.ms/u/s!ApqQOqYhGvWHget1A4YRqyzT3a9BEQ?e=9UJB0R
import flash.display.Sprite;
import flash.display.MovieClip;
/*;
choValues = {
"apple": 15,
"bakedBeans": 15,
"chickenLeg": 0,
"chickenNuggets": 15,
"cornOnTheCob": 15,
"egg": 0,
"grapes": 5,
"hamburger": 30,
"milkFull": 24,
"juiceFull": 30,
"juiceHalf": 15,
"saltineCrackers": 5,
"orange": 15,
"tomato": 5
}*/
var foodNames:Array = new Array();
var choValues:Array = new Array();
var options:Array = new Array();
var index:Array = new Array();
var shelves:MovieClip = new Shelves();
var plate:MovieClip = new Plate();
var plateSlots:Array = [0,0,0,0];
var iconSize:Array = new Array();
trace(stage.stageWidth);
trace(stage.stageHeight);
var relativeWidth:Number = stage.stageWidth/32;
var relativeHeight:Number = stage.stageHeight/32;
trace("shelves");
trace(shelves.x = relativeWidth*4 );
trace(shelves.y = relativeHeight*8);
trace(shelves.width = relativeWidth*10);
trace(shelves.height = relativeHeight*14);
stage.addChildAt(shelves,1);
trace("plate");
plate.instanceName = "plate";
trace(plate.x = relativeWidth*15 );
trace(plate.y = relativeHeight*8);
trace(plate.width = relativeWidth*10);
trace(plate.height = relativeHeight*14);
plate.name = "plate";
stage.addChildAt(plate,0);
trace("plate.name "+ plate.name);
/*var fruit = new orange;
trace("fruit");
trace(fruit.x = plate.width/2);
trace(fruit.y = plate.height/2);
//trace(plateSlots.width = plate.width/2);
//trace(plateSlots.height = plate.height/2);*/
//plate.addChild(fruit);
function drag (e:MouseEvent):void //find the slot
{
e.currentTarget.startDrag();
trace("drag "+e.currentTarget.name);
trace("Classname "+ getQualifiedClassName(e.currentTarget));
}
function drop (e:MouseEvent):void
{
e.currentTarget.stopDrag();
trace("drop Classname "+ getQualifiedClassName(e.currentTarget));
trace("drop name "+ (e.currentTarget.name));
//if(e.currentTarget.dropTarget !=null)
//if(e.currentTarget.dropTarget.parent !=null)
//if(e.currentTarget.dropTarget.parent.parent != null)
try{if (e.currentTarget.dropTarget.parent.parent.name == "plate")
{
trace("currentTarget is "+e.currentTarget);
var mc:MovieClip = MovieClip(e.currentTarget);
trace(mc);
trace("mc is movieClip?" + (mc is MovieClip));
trace("is plate");
for (var i=0; i<4; i++)
{
if (plateSlots[i] == 0)
{
trace(mc);
//shelves.removeChild(mc);
plate.addChild(mc);
//e.currentTarget.width = iconSize[0];
//e.currentTarget.height = iconSize[1];
trace(mc.x = plate.width/6 + ((i%2)*plate.width/8));
trace(mc.y = plate.height/6 + ((i<2 ? 0:1)*plate.height/4));
plateSlots[i] = 1;
mc.slot = i;
return;
}
}
}
else{
shelves.addChild(e.currentTarget as MovieClip);
e.currentTarget.x = e.currentTarget.oldX;
e.currentTarget.y = e.currentTarget.oldY;
}
}
catch(e:Error){}
shelves.addChild(e.currentTarget as MovieClip);
e.currentTarget.x = e.currentTarget.oldX;
e.currentTarget.y = e.currentTarget.oldY;
}
function randomize ( a : *, b : * ) : int {
return ( Math.random() > .5 ) ? 1 : -1;
}
foodNames.push(
"apple","bakedBeans","chickenLeg",
"chickenNuggets","cornOnTheCob","egg",
"grapes","hamburger","milkFull",
"juiceFull","juiceHalf","saltineCrackers",
"orange","tomato"
)
choValues.push(
15,15,0,
15,15,0,
5,30,24,
30,15,5,
15,5
)
for (var i:int=1; i<foodNames.length; i++)
{
index.push(i);
}
index.sort(randomize);
trace(index);
for(i=0; i<8; i++)
{
options[index[i]] = new (getDefinitionByName(foodNames[index[i]]));
trace("class "+getDefinitionByName(foodNames[index[i]]));
options[index[i]].addEventListener(MouseEvent.MOUSE_DOWN, drag);
options[index[i]].addEventListener(MouseEvent.MOUSE_UP, drop);
options[index[i]].CHO = choValues[i];
options[index[i]].x += ( (2*(i%4)) +1 ) *(shelves.width /10);
options[index[i]].y = ( ( i<4 ) ? 17 : 37 )*(shelves.height/64);
options[index[i]].oldX = options[index[i]].x;
options[index[i]].oldY = options[index[i]].y;
shelves.addChild(options[index[i]]);
}
//iconSize[0] = options[index[0]].width;
//iconSize[1] = options[index[0]].height;
stop();

Related

How to create a hierarchy Menu/Icon

I dont know if the question represent exactly what i want to ask, but i could`t figure how else to name what i want to do.
So im trying to create a 3x3 grid and in every cell i have a image.
I can click on any of the 2nd cell of a column only if the 1st of the same column has been clicked before that.What i mean is
i can click cell No:5 only if 4 has been clicked before that
i can click cell No:9 only if 8 and 7 has been clicked before that
i can click cell No:1,4,7 anytime.
and also when they are clicked their alpha gets to 0.1 (so i know that the cell has been clicked.)
currently i the logic for creating the grid and changing the alpha of any object i click but i don`t have the logic for the hierarchy.
public function Main()
{
var index:int = 0
var col:int = 3
var row:int = 3
for (var i:int = 0; i < row; i++)
{
for (var j:int = 0; j < col; j++)
{
var cls:Class = Class(getDefinitionByName("Bitmap" + (index + 1) ));
myImage = new Bitmap( new cls() );
var myImage_mc:MovieClip = new MovieClip();
myImage_mc.addChild(myImage)
myImage_mc.x = 100 + i * (myImage_mc.width + 10)
myImage_mc.y = 100 + j * (myImage_mc.height + 10)
this.addChild(myImage_mc);
myImage_mc.mouseEnabled = true
myImage_mc.addEventListener(MouseEvent.CLICK, onClick);
index++
}
}
}
private function onClick(ev:MouseEvent):void
{
trace(ev.target.name)
ev.currentTarget.alpha = 0.1;
}
Another way is to use a link variable to link element.
public class BitmapButton extends Sprite {
public var next:BitmapButton = null;
}
public class Main extends Sprite {
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);
var index:int = 0
var col:int = 3
var row:int = 3
for (var j:int = 0; j < col; j++)
{
var lastRowElement:BitmapButton = null;
for (var i:int = 0; i < row; i++)
{
var bmpd:BitmapData = new BitmapData( 100, 100, false, Math.floor( 0xff + Math.random() * 0xffffff ) );
var myImage:Bitmap = new Bitmap( bmpd );
var myImage_mc:BitmapButton = new BitmapButton();
myImage_mc.addChild(myImage)
myImage_mc.x = 100 + j * (myImage_mc.width + 10);
myImage_mc.y = 100 + i * (myImage_mc.height + 10);
myImage_mc.name = i + "_" + j;
this.addChild(myImage_mc);
myImage_mc.mouseChildren = false;
myImage_mc.mouseEnabled = false;
myImage_mc.addEventListener(MouseEvent.CLICK, onClick);
if ( lastRowElement == null ) {
myImage_mc.mouseEnabled = true;
} else {
lastRowElement.next = myImage_mc;
}
lastRowElement = myImage_mc;
index++
}
}
}
private function onClick(ev:MouseEvent):void
{
trace(ev.target.name)
if ( ev.target is BitmapButton ) {
var btn:BitmapButton = ev.target as BitmapButton;
ev.currentTarget.alpha = 0.1;
if( btn.next != null ) {
btn.next.mouseEnabled = true;
}
}
}
}
Something like this
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.utils.Dictionary;
public class Grid extends Sprite
{
private var _box : Dictionary = new Dictionary;
private var _conditions : Dictionary = new Dictionary;
private var _clicked : Dictionary = new Dictionary;
public function Grid()
{
var index:int = 0
var col:int = 3
var row:int = 3
for (var i:int = 0; i < row; i++)
{
for (var j:int = 0; j < col; j++)
{
//var cls:Class = Class(getDefinitionByName("Bitmap" + (index + 1) ));
//myImage = new Bitmap( new cls() );
var myImage_mc:MovieClip = new MovieClip();
//myImage_mc.addChild(myImage)
_box[ index ] = myImage_mc;
// Conditions for the 2nd and 3nd line etc.
if( i != 0 )
_conditions[ myImage_mc ] = _box[ index - col ];
// ------ DEBUG
myImage_mc.graphics.beginFill( 0xFFFFFF * Math.random() );
myImage_mc.graphics.drawRect(0,0,100,100);
myImage_mc.graphics.endFill();
// ------ END DEBUG
// Note i / j are invert from your example
myImage_mc.x = 100 + j * (myImage_mc.width + 10);
myImage_mc.y = 100 + i * (myImage_mc.height + 10);
this.addChild(myImage_mc);
myImage_mc.mouseEnabled = true
myImage_mc.addEventListener(MouseEvent.CLICK, onClick);
index++
}
}
}
protected function onClick(ev:MouseEvent):void
{
var neededClickElement : MovieClip = _conditions[ ev.currentTarget ];
// Check if we need an active movieclip before
if( neededClickElement != null && ! _clicked[ neededClickElement ] )
return;
_clicked[ ev.currentTarget ] = true;
ev.currentTarget.alpha = 0.1;
}
}
}

User interaction with Leapmotion AS3 library

I can connect the device and attach a custom cursor to one finger, but I can´t use any of the gestures to over/click a button or drag a sprite around, etc.
I´m using Starling in the project. To run this sample just create a Main.as, setup it with Starling and call this class.
My basic code:
package
{
import com.leapmotion.leap.Controller;
import com.leapmotion.leap.events.LeapEvent;
import com.leapmotion.leap.Finger;
import com.leapmotion.leap.Frame;
import com.leapmotion.leap.Gesture;
import com.leapmotion.leap.Hand;
import com.leapmotion.leap.InteractionBox;
import com.leapmotion.leap.Pointable;
import com.leapmotion.leap.ScreenTapGesture;
import com.leapmotion.leap.Vector3;
import starling.display.Shape;
import starling.display.Sprite;
import starling.events.Event;
import starling.events.TouchEvent;
/**
* ...
* #author miau
*/
public class LeapController extends Sprite
{
private var _controller:Controller;
private var _cursor:Shape;
private var _screenTap:ScreenTapGesture;
private var _displayWidth:uint = 800;
private var _displayHeight:uint = 600;
public function LeapController()
{
addEventListener(Event.ADDED_TO_STAGE, _startController);
}
private function _startController(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, _startController);
//adding controller
_controller = new Controller();
_controller.addEventListener( LeapEvent.LEAPMOTION_INIT, onInit );
_controller.addEventListener( LeapEvent.LEAPMOTION_CONNECTED, onConnect );
_controller.addEventListener( LeapEvent.LEAPMOTION_DISCONNECTED, onDisconnect );
_controller.addEventListener( LeapEvent.LEAPMOTION_EXIT, onExit );
_controller.addEventListener( LeapEvent.LEAPMOTION_FRAME, onFrame );
//add test button
_testButton.x = stage.stageWidth / 2 - _testButton.width / 2;
_testButton.y = stage.stageHeight / 2 - _testButton.height / 2;
addChild(_testButton);
_testButton.touchable = true;
_testButton.addEventListener(TouchEvent.TOUCH, doSomething);
//draw ellipse as a cursor
_cursor = new Shape();
_cursor.graphics.lineStyle(6, 0xFFE24F);
_cursor.graphics.drawEllipse(0, 0, 80, 80);
addChild(_cursor);
}
private function onFrame(e:LeapEvent):void
{
trace("ON FRAME STARTED");
var frame:Frame = e.frame;
var interactionBox:InteractionBox = frame.interactionBox;
// Get the first hand
if(frame.hands.length > 0){
var hand:Hand = frame.hands[0];
var numpointables:int = e.frame.pointables.length;
var pointablesArray:Array = new Array();
if(frame.pointables.length > 0 && frame.pointables.length < 2){
//trace("number of pointables: "+frame.pointables[0]);
for(var j:int = 0; j < frame.pointables.length; j++){
//var pointer:DisplayObject = pointablesArray[j];
if(j < numpointables){
var pointable:Pointable = frame.pointables[j];
var normal:Vector3 = pointable.tipPosition;
var normalized:Vector3 = interactionBox.normalizePoint(normal);
//pointable.isFinger = true;
_cursor.x = normalized.x * _displayWidth;
_cursor.y = _displayHeight - (normalized.y * _displayHeight);
_cursor.visible = true;
}else if (j == 0) {
_cursor.visible = false;
}
}
}
}
}
private function onExit(e:LeapEvent):void
{
trace("ON EXIT STARTED");
}
private function onDisconnect(e:LeapEvent):void
{
trace("ON DISCONNECT STARTED");
}
private function onConnect(e:LeapEvent):void
{
trace("ON CONNECT STARTED");
_controller.enableGesture( Gesture.TYPE_SWIPE );
_controller.enableGesture( Gesture.TYPE_CIRCLE );
_controller.enableGesture( Gesture.TYPE_SCREEN_TAP );
_controller.enableGesture( Gesture.TYPE_KEY_TAP );
}
private function onInit(e:LeapEvent):void
{
trace("ON INIT STARTED");
}
private function doSomething(e:TouchEvent):void
{
trace("I WAS TOUCHED!!!");
}
}
}
If a good code Samaritan can update this code to perform a screen tap gesture (or any interacion with any object), I will really appreciate this a lot.
Regards!
controller.enableGesture(Gesture.TYPE_SWIPE);
controller.enableGesture(Gesture.TYPE_SCREEN_TAP);
if(controller.config().setFloat("Gesture.Swipe.MinLength", 200.0) && controller.config().setFloat("Gesture.Swipe.MinVelocity", 500)) controller.config().save();
if(controller.config().setFloat("Gesture.ScreenTap.MinForwardVelocity", 30.0) && controller.config().setFloat("Gesture.ScreenTap.HistorySeconds", .5) && controller.config().setFloat("Gesture.ScreenTap.MinDistance", 1.0)) controller.config().save();
//etc...
Then catch it in the frame event listener:
private function onFrame( event:LeapEvent ):void
{
var frame:Frame = event.frame;
var gestures:Vector.<Gesture> = frame.gestures();
for ( var i:int = 0; i < gestures.length; i++ )
{
var gesture:Gesture = gestures[ i ];
switch ( gesture.type )
{
case Gesture.TYPE_SCREEN_TAP:
var screentap:ScreenTapGesture = ScreenTapGesture ( gesture);
trace ("ScreenTapGesture-> x: " + Math.round(screentap.position.x ) + ", y: "+ Math.round( screentap.position.y));
break;
case Gesture.TYPE_SWIPE:
var screenSwipe:SwipeGesture = SwipeGesture(gesture);
if(gesture.state == Gesture.STATE_START) {
//
}
else if(gesture.state == Gesture.STATE_STOP) {
//
trace("SwipeGesture-> direction: "+screenSwipe.direction + ", duration: " + screenSwipe.duration);
}
break;
default:
trace( "Unknown gesture type." )
}
}
}
When the event occurs, check the coordinates translated to the stage/screen and whether a hit test returns true.
EDIT: Considering I have no idea how to reliable get the touch point x/y (or better: how to translate them to the correct screen coordinates), I would probably do something like this in my onFrame event:
private function onFrame(event:LeapEvent):void {
var frame:Frame = event.frame;
var gestures:Vector.<Gesture> = frame.gestures();
var posX:Number;
var posY:Number;
var s:Shape;
if(frame.pointables.length > 0) {
var currentVector:Vector3 = screen.intersectPointable(frame.pointables[0], true); //get normalized vector
posX = 1920 * currentVector.x - stage.x; //NOTE: I hardcoded the screen res value, you can get it like var w:int = leap.locatedScreens()[0].widthPixels();
posY = 1080 * ( 1 - currentVector.y ) - stage.y; //NOTE: I hardcoded the screen res value, you can get it like var h:int = leap.locatedScreens()[0].heightPixels();
}
for(var i:int = 0; i < gestures.length; i++) {
var gesture:Gesture = gestures[i];
if(gesture.type == Gesture.TYPE_SCREEN_TAP) {
if(posX >= _button1.x &&
posX <= _button1.x + _button1.width &&
posY >= _button1.y &&
posY <= _button1.y + _button1.height) {
s = new Shape();
s.graphics.beginFill(0x00FF00);
s.graphics.drawCircle(0, 0, 10);
s.graphics.endFill();
s.x = posX;
s.y = posY;
stage.addChild(s);
trace("Lisa tocada!");
}
else {
s = new Shape();
s.graphics.beginFill(0xFF0000);
s.graphics.drawCircle(0, 0, 10);
s.graphics.endFill();
s.x = posX;
s.y = posY;
stage.addChild(s);
trace("Fallaste! Intentalo otra vez, tiempo: "+new Date().getTime());
}
}
}
}

Timer related error in flash, TypeError #1009

I used a timer in my flash application, and I have this particular error below:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at FlashGame_fla::MainTimeline/toTimeCode()
at FlashGame_fla::MainTimeline/timerTickHandler()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
Below is my code for this particular flash game application. It's a game where the player collects as many items as possible within a specific time:
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.geom.Rectangle;
menuButton.addEventListener(MouseEvent.CLICK, evilToMenu);
rulesButton.addEventListener(MouseEvent.CLICK, toggleRule);
gameRules.addEventListener(MouseEvent.CLICK, toggleRule);
gameRules.visible = false;
gameRules.buttonMode = true;
evilGameOverMC.visible = false;
evilWinLose.visible = false;
playAgainBtn.visible = false;
toMenuBtn.visible = false;
var pLives:int = 3;
var pEvilScore:int = 0;
var pItems:int = 10;
var daveMC:MovieClip;
var cGameObjs:Array = new Array();
var timer:Timer = new Timer(100, 300);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 15000;
//var cPlayerData:Object;
//var cSavedGameData:SharedObject;
addCharacter();
addBots();
addItems();
scoreDisplay.text = "" + pEvilScore;
livesDisplay.text = pLives + " lives";
function evilToMenu(Event:MouseEvent):void
{
removeLeftovers();
removeChild(daveMC);
timer.stop();
gotoAndStop("menu");
}
function timerTickHandler(Event:TimerEvent):void
{
timerCount -= 100;
toTimeCode(timerCount);
if (timerCount <= 0)
{
gameOver(false);
}
}
function toTimeCode(milliseconds:int): void
{
//creating a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
//define minutes/seconds/mseconds
var minutes:String = String(time.minutes);
var seconds:String = String(time.seconds);
var miliseconds:String = String(Math.round(time.milliseconds)/100);
//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+minutes : minutes;
seconds = (seconds.length != 2) ? '0'+seconds : seconds;
//display elapsed time on in a textfield on stage
timerDisplay.text = minutes + ":" + seconds;
}
function addCharacter():void
{
trace("Adding the character, Dave")
//set the initial values
var myBorder:Rectangle = new Rectangle(355,145,395,285);
var myXY:Array = [355,430];
var myChar:int = Math.ceil(Math.random() * 3);
var myKeys:Array = [37,39,38,40];
var myDistance:int = 7;
// create and add a new player object to the stage
daveMC = new Character(myBorder,myXY,myKeys,myChar,myDistance);
addChild(daveMC);
}
function addBots():void
{
trace("Adding the bots..");
// set the initial values (adapt to suit your game)
var myBorder:Rectangle = new Rectangle(355,145,395,285);
var myMaxBots:int = 5;// simulation
// add bots one at a time via a loop
for (var i:int = 0; i < myMaxBots; i++)
{
// create a new bot object and name it
var thisBot:Bot = new Bot(myBorder, daveMC);
thisBot.name = "bot" + i;
cGameObjs.push(thisBot);
// add it to the stage
addChild(thisBot);
}
}
function addItems():void
{
trace("Adding the items..");
//set the initial values
for (var i:int = 0; i < 10; i++)
{
// create a new bot object and name it
var thisItem:Item = new Item(daveMC);
thisItem.name = "item" + i;
cGameObjs.push(thisItem);
// add it to the stage
addChild(thisItem);
}
}
function updateLives(myBot:MovieClip):void
{
// update the player's LIVES and score
pLives--;
pEvilScore -= 30;
var myIndex:int = cGameObjs.indexOf(myBot);
cGameObjs.splice(myIndex,1);
// check for a LOST GAME
if (pLives > 0)
{
updateScores();
}
else
{
gameOver(false);
}
}
function updateItems(myItem:MovieClip):void
{
// update the player's LIVES and score
pItems--;
pEvilScore += 20;
var myIndex:int = cGameObjs.indexOf(myItem);
cGameObjs.splice(myIndex,1);
// check for a LOST GAME
if (pItems > 0)
{
updateScores();
}
else
{
gameOver(true);
}
}
function gameOver(myFlag:Boolean):void
{
updateScores();
if (myFlag)
{
// player wins
msgDisplay.text = "YAY! PAPPLE FOR \nEVERYBODY!";
removeLeftovers();
evilWinLose.text = "Weee!! We've got papples for Gru! \nYour Score: " + pEvilScore;
}
else
{
// player loses
msgDisplay.text = "OH NO! NOT \nENOUGH PAPPLES";
removeLeftovers();
evilWinLose.text = "Boo!! Not enough papples for Gru! \nYour Score: " + pEvilScore;
}
timerDisplay.text = "";
removeChild(daveMC);
evilGameOverMC.visible = true;
evilWinLose.visible = true;
toMenuBtn.visible = true;
playAgainBtn.visible = true;
toMenuBtn.addEventListener(MouseEvent.CLICK, Click_backtoMain);
playAgainBtn.addEventListener(MouseEvent.CLICK, backToEvil);
}
function updateScores():void
{
scoreDisplay.text = "" + pEvilScore;
livesDisplay.text = pLives + " lives";
msgDisplay.text = pItems + " papples more to \ncollect..";
}
function removeLeftovers():void
{
// check each BOT/ITEM in array
for each (var myObj in cGameObjs)
{
myObj.hasHitMe();
myObj = null;
}
}
function backToEvil(event:MouseEvent):void
{
pEvilScore = 0;
pLives = 3;
pItems = 3;
gotoAndStop("menu");
gotoAndStop("evil");
}
Anyone can help me out with this? Thank you alot! :)
Replace your toTimeCode function code by :
function toTimeCode(milliseconds:int): void
{
trace(1);
//creating a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
trace(2);
//define minutes/seconds/mseconds
var minutes:String = String(time.minutes);
trace(3);
var seconds:String = String(time.seconds);
trace(4);
var miliseconds:String = String(Math.round(time.milliseconds)/100);
trace(5);
//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+minutes : minutes;
trace(6);
seconds = (seconds.length != 2) ? '0'+seconds : seconds;
trace(7);
//display elapsed time on in a textfield on stage
timerDisplay.text = minutes + ":" + seconds;
trace(8);
}
Please, change the timerDisplay line to this one... The problem will be in the toTimeCode method. The error say that you are trying to call a method from a var wich is not (yet) an object...
if(null != timerDisplay)
timerDisplay.text = minutes + ":" + seconds;
You have to find an object wich is null! Add this :
function toTimeCode(milliseconds:int): void
{
//creating a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
trace("Time: " + time);

Flash only removing objects not created through code

I'm trying to make a simple game in Flash. So far, I've added a bunch of objects to the stage using addChild(objName);. However, now I'm trying to remove the objects completely. I don't want to have to cycle through every object's name and I'm sure there must be a more efficient way to select each object (maybe by index on the stage) and removeChildAt(index); it. However, when I try this, Flash only removes the objects that were manually placed by me on the stage. It doesn't remove the ones that were placed through code. I've done some searching and I tried multiple methods, all of which yield the same result. The one that most people agree on is this one:
while (numChildren > 0)
{
removeChildAt(0);
}
Can you help me figure out why this isn't removing anything that was coded onto the stage?
Thanks in advance :D
Edit: Here is my code for the frames:
Frame 1 (Randomly generates and displays the dots):
import flash.events.MouseEvent;
import fl.motion.easing.Linear;
var dotList = new Array(); var level:int = 3; var invisoDotList = new Array();
var loop:int;
var line:Line = new Line();
line.x = 274;
line.y = 187;
addChild(line);
for(loop = 0; loop < level; loop++)
{
var dot:Dot = new Dot();
var invisoDot:InvisoDot = new InvisoDot();
var tester:Boolean = true;
var xval:int = Math.floor(Math.random()*(1+520))+14;
var looper:int = 0;
while(looper < dotList.length)
{
if(Math.abs(xval - dotList[looper].x) > 30)//minimum spacing
{
looper++;
}
else
{
looper = 0;
xval = Math.floor(Math.random()*(1+520))+14;
}
}
dot.x = xval;
dot.y = 187;
invisoDot.x = xval;
invisoDot.y = 187;
invisoDot.alpha = 0;
dotList[loop] = dot;
invisoDotList[loop] = invisoDot;
addChild(invisoDot);
addChild(dot);
}
//trace(dotList); test to ensure that dots are added to the array
var nb1:NextButton = new NextButton();
nb1.x = 0;
nb1.y = 0;
nb1.alpha = 0;
addChild(nb1);
nb1.addEventListener(MouseEvent.CLICK, hideDots);
function hideDots(e:MouseEvent)
{
for(var loop:int = 0; loop < dotList.length; loop++)
{
dotList[loop].alpha = 0;//make dots disappear
}
line.alpha = 0;
nextFrame();
}
stop();
Frame 2 (Displays further instructions and contains a couple of methods that will be used later on):
import flash.events.MouseEvent;
removeChild(nb1);
var nb2:NextButton = new NextButton();
nb2.x = 0;
nb2.y = 0;
nb2.alpha = 0;
addChild(nb2);
nb2.addEventListener(MouseEvent.CLICK, next);
function next(e:MouseEvent)
{
nextFrame();
}
function clearStage()
{
while (numChildren > 0)
{
trace("before" + numChildren);
removeChildAt(0);
trace("after" + numChildren);
}
}
stop();
Frame 3 (Makes the dots disappear when they are clicked and keeps an accuracy count):
import flash.events.MouseEvent;
import flash.utils.Timer;
line.alpha = 1;
removeChild(nb2);
//setChildIndex(line,0);
var clicks:int = -1;
var passed:int = 0;
var fromLine:Boolean = false;
//trace(dotList.length);
stage.addEventListener(MouseEvent.CLICK, clickCount);
for(var loopvar:int = 0; loopvar < dotList.length; loopvar++)
{
//trace("loop");
dot = dotList[loopvar];
invisoDot = invisoDotList[loopvar];
dot.addEventListener(MouseEvent.CLICK, onClick);
invisoDot.addEventListener(MouseEvent.CLICK, onClick);
//trace("event");
}
//trace(dotList.length);
function onClick(e:MouseEvent)
{
//e.currentTarget.alpha = .5;
for(var hitcheck:int = 0; hitcheck < dotList.length; hitcheck++)
{
if(dotList[hitcheck].x == e.currentTarget.x)
{
dotList[hitcheck].alpha = 1;
}
}
//trace("check");
}
var numChanged:int = 0;
function clickCount(e:MouseEvent)
{
clicks++;
//trace(clicks);
numChanged = 0;
for(var index:int = 0; index < dotList.length; index++)//check whether the user has gotten all the dots
{
if(dotList[index].alpha == 1)
{
numChanged++;
}
}
if(numChanged == level)//if the user has gotten all the dots
{
/*trace("next screen for sucess");
trace(clicks);*/
line.visible = false;
for(loop = 0; loop < dotList.length; loop++)
{
dotList[loop].alpha = 0;//make dots disappear
}
if((clicks - level) == 1)
{
passed = 2
}
else if((clicks - level) == 0)
{
passed = 1;
}
passed = 1;
fromLine = true;
nextFrame();
}
else if((clicks - numChanged) >= 2)//this ends the session as soon as 2 mistakes are made
{
/*trace("next screen for failed number of clicks");
trace(clicks);*/
line.visible = false;
for(loop = 0; loop < dotList.length; loop++)
{
dotList[loop].alpha = 0;//make dots disappear
}
passed = 3;
fromLine = true;
nextFrame();
}
/*else if((clicks - level) >= 2)//if the user has made too many mistakes. This ends the session after the maximum number of tries have been used
{
trace("next screen too many clicks");
trace(clicks);
}*/
}
//trace("end");
stop();
Frame 4 (Generates the results table. A sidenote: there is a bug where "Okay" is never a result because in Frame 3, the value of passed never equals 2. Not sure why though):
import flash.text.TextFormat;
import flash.text.TextField;
var failFormat:TextFormat = new TextFormat();
failFormat.color = 0xFF0000;
failFormat.font = "Arial";
failFormat.size = 18;
var passFormat:TextFormat = new TextFormat();
passFormat.color = 0x00FF00;
passFormat.font = "Arial";
passFormat.size = 18;
var okayFormat:TextFormat = new TextFormat();
okayFormat.color = 0x808000;
okayFormat.font = "Arial";
okayFormat.size = 18;
var normalFormat:TextFormat = new TextFormat();
normalFormat.color = 0x000000;
normalFormat.font = "Arial";
normalFormat.size = 18;
var lineResults = new Array();
var squareResults = new Array();
trace(passed);
if(fromLine == true)
{
if(passed == 1)
{
lineResults[lineResults.length] = "Pass";
}
else if(passed == 2)
{
lineResults[lineResults.length] = "Okay";
}
else if(passed == 3)
{
lineResults[lineResults.length] = "Fail";
}
}
fromLine = false;
lineResults = lineResults.reverse();
squareResults = squareResults.reverse();
var loopLength:int = (lineResults.length >= squareResults.length) ? lineResults.length : squareResults.length;
var loopStart:int = 0;
if(loopLength > 11)
{
loopStart = loopLength - 12
}
var cb:CellBlock = new CellBlock();
cb.x = 283.05;
cb.y = 20.35;
addChild(cb);
var col1Head:TextField = new TextField();
col1Head.defaultTextFormat = normalFormat;
col1Head.text = "# of Dots";
col1Head.x = 114.95
col1Head.y = 8.3;
addChild(col1Head);
var col2Head:TextField = new TextField();
col2Head.defaultTextFormat = normalFormat;
col2Head.text = "Line";
col2Head.x = 259.95
col2Head.y = 8.3;
addChild(col2Head);
var col3Head:TextField = new TextField();
col3Head.defaultTextFormat = normalFormat;
col3Head.text = "Square";
col3Head.x = 381.95
col3Head.y = 8.3;
addChild(col3Head);
for(loop = loopStart; loop < loopLength; loop++)
{
var block:CellBlock = new CellBlock();
block.x = 283.05;
block.y = 20.35 + (loop - loopStart + 1)*33;
addChild(block);
var col2:TextField = new TextField();
var col3:TextField = new TextField();
var col1:TextField = new TextField();
/*col2.defaultTextFormat = passFormat;
col3.defaultTextFormat = okayFormat;*/
col1.defaultTextFormat = normalFormat;
switch(lineResults[loop])
{
case "Pass":
col2.defaultTextFormat = passFormat;
break;
case "Okay":
col2.defaultTextFormat = okayFormat;
break;
case "Fail":
col2.defaultTextFormat = failFormat;
break;
}
switch(squareResults[loop])
{
case "Pass":
col3.defaultTextFormat = passFormat;
break;
case "Okay":
col3.defaultTextFormat = okayFormat;
break;
case "Fail":
col3.defaultTextFormat = failFormat;
break;
}
//col2.text = "Pass";
col2.text = lineResults[loop];
col2.x = 260.95;
col2.y = block.y - 12;
addChild(col2);
//col3.text = "Okay";
try
{
col3.text = squareResults[loop];
}
catch(e:Error)
{
}
col3.x = 386.95;
col3.y = block.y - 12;
addChild(col3);
col1.text = String(loop + 1);
col1.x = 133.95;
col1.y = block.y - 12;
addChild(col1);
}
var nb4:NextButton = new NextButton();
nb4.x = 0;
nb4.y = 0;
nb4.alpha = 0;
addChild(nb4);
nb4.addEventListener(MouseEvent.CLICK, clearStage);
stop();
Frame 5 (Next frame which is a test to make sure that everything gets erased, which it doesn't):
removeChild(nb4);
stop();
This error:
ArgumentError: Error #1063: Argument count mismatch on Game_fla::MainTimeline/clearStage(). Expected 0, got 1. clearStage()
Occurs because your clearStage() method has been added as the click event handler of a button. If your clearStage() function is going to be used an an event handler, it needs to accept an "event" parameter. So you should define the function like this:
function clearStage(event:Event)
{
while (numChildren > 0)
{
trace("before" + numChildren);
removeChildAt(0);
trace("after" + numChildren);
}
}
As a side note, this means that if you want to also call clearStage() manually, that is use it without adding it as an event handler, that you'll need to include this event parameter... but you can just pass in a null, because your code doesn't need to actually use the event parameter:
clearStage(null);
I'm not sure I see anything else wrong. I'd start by adding that event parameter to your clearStage() function as I shown above.
I should also add I mostly worked in Flex or pure AS3, and am not super skilled in Flash CS6 and programming on the timeline :)
From memory, I don't think Flash re-orders when you remove a child. If you remove a child at index 0, every other child is still numbered 1 to x. childAt(0) is just null now. Keep that in mind with this sort of process.

Flash CS5 AS3 Can not get Flashvars

I am new to fairly new to AS3 and I have found myself needing to extend a fla. that was written by a 3rd party.
The goal is to access flashvars but for the life of me can not get it to work...been at it for days learning..
the fla I am working with is code on timeline with 2 frames. the movieclip runs to frame 2 ans stops.
On frame 2 is where I require the use of the flashvar.
I have built a simple example that will populate a textbox on frame two that works fine.
frame 1
var my_var:String = new String();
my_var = root.loaderInfo.parameters.uploadId;
frame 2
my_txt.text = my_var;
stop();
However when I use the same approach on my 3rd party fla I get NULL output. I am not using any TLF text either (I think).
I don't understand why it works in one case but not the other. I am thinking it might have to do with conflict with the surrounding code but I don't know enough about AS to track it down. Any help on this would be greatly appreciated.
frame 1
import net.bizmodules.uvg.loading;
stop();
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.showDefaultContextMenu = false;
stage.quality = StageQuality.BEST;
function RandomValue()
{
var d = new Date();
return String(d.getDate()) + String(d.getHours()) + String(d.getMinutes()) + String(d.getSeconds());
}
var my_var:String;
my_var = root.loaderInfo.parameters.uploadId;
var userId;
var albums:Object;
var resource:Object;
var strUploadPage:String;
if (root.loaderInfo.parameters.uploadPage != undefined)
strUploadPage = root.loaderInfo.parameters.uploadPage;
else
strUploadPage = "http://localhost/dnn450/desktopmodules/ultramediagallery/flashuploadpage.aspx?PortalId=0&ModuleId=455";
if (strUploadPage.indexOf("?") > 0)
strUploadPage += "&";
else
strUploadPage += "?";
strUploadPage += "action=loadAlbums&seed=" + RandomValue();
trace(strUploadPage);
var myLoading:MovieClip = new loading();
myLoading.x = (stage.stageWidth - myLoading.width) / 2;
myLoading.y = (stage.stageHeight - myLoading.height) / 2;
addChild(myLoading);
var myRequest:URLRequest = new URLRequest(strUploadPage);
var myLoader:URLLoader = new URLLoader(myRequest);
myLoader.addEventListener(Event.COMPLETE, xmlLoaded);
function xmlLoaded(evtObj:Event)
{
myLoader.removeEventListener(Event.COMPLETE, xmlLoaded);
try
{
var xDoc:XMLDocument = new XMLDocument();
xDoc.ignoreWhite = true;
var xml:XML = XML(myLoader.data);
xDoc.parseXML(xml.toXMLString());
userId=xDoc.firstChild.attributes.userId;
if (userId < 0)
{
removeChild(myLoading);
txtError.text = "Please ensure you are logged in";
return;
}
if(xDoc.firstChild.childNodes.length > 0)
{
albums = xDoc.firstChild.childNodes[0].childNodes;
resource = xDoc.firstChild.childNodes[1].attributes;
}
else
{
removeChild(myLoading);
txtError.text = xDoc.firstChild.attributes.error;
return;
}
play();
}
catch(e:Error)
{
removeChild(myLoading);
txtError.text = e + "\n\nPlease check your Event Viewer to find out detailed error message and contact service#bizmodules.net";
}
}
frame 2
import net.bizmodules.upg.Alert;
stop();
removeChild(myLoading);
initialize();
function initialize()
{
Alert.init(stage);
upload.addVar("userId",userId);
lstAlbums.dropdown.rowHeight = 24;
loadAlbums(0, albums);
var my_so:SharedObject = SharedObject.getLocal("UPGUpload");
var lastAlbum = my_so.data.lastAlbum * 1;
var foundLastAlbum = false;
if (lastAlbum > 0)
{
for (var i:int = 0; i< lstAlbums.length; i++)
{
if (lstAlbums.getItemAt(i).data == lastAlbum)
{
trace("find previous album");
foundLastAlbum = true;
lstAlbums.selectedIndex = i;
break;
}
}
}
if (!foundLastAlbum)
{
lstAlbums.selectedIndex = lstAlbums.length - 1;
}
albums_change(null);
lstAlbums.addEventListener("change", albums_change);
lstAlbums.setStyle("backgroundColor", 0x504C4B);
lstAlbums.dropdown.setStyle("backgroundColor", 0x504C4B);
lstAlbums.setStyle("themeColor", 0x1F90AE);
lstAlbums.setStyle("color", 0xC4C0BF);
lstAlbums.setStyle("textSelectedColor", 0xC4C0BF);
lstAlbums.setStyle("textRollOverColor", 0xC4C0BF);
lstAlbums.setStyle("alternatingRowColors", [0x504C4B, 0x504C4B]);
lstAlbums.setStyle("borderStyle", 'none');
}
my_txt.text = "hello" + " " + my_var;
function loadAlbums(level:int, xml:Object)
{
var prefix = " ".substring(0, level * 4);;
for (var i:int = 0;i<xml.length;i++)
{
var itemValue = xml[i].attributes.itemid;
if (xml[i].childNodes.length > 0)
itemValue *= -1;
lstAlbums.addItem({data: itemValue, label: prefix + xml[i].attributes.name});
if (xml[i].childNodes.length > 0)
{
loadAlbums(level + 1, xml[i].childNodes);
}
}
}
function albums_change(e)
{
var albumId = lstAlbums.getItemAt(lstAlbums.selectedIndex).data;
upload.set_albumId(albumId);
if (albumId > 0)
{
var my_so:SharedObject = SharedObject.getLocal("UPGUpload");
my_so.data.lastAlbum = albumId;
}
else
{
Alert.show("The album you choosed is invalid", null, 0xEAEAEA, 0x000000);
}
}
private var flashVarObj:Object = new Object;
flashVarObj=LoaderInfo(this.loaderInfo).parameters;
var my_var:String = new String();
my_var = flashVarObj.uploadIdd;