I cant remove child of this movie clip upon clicking the back button to go function goHomePage (evt:Event):void{ - actionscript-3

Help. I need to remove the newContainer(this is a movie clip) after clicking the back button to go back to homepage.
But it just loads the homepage and the newContainer is still there. :( where did i go wrong?
import flash.events.MouseEvent;
import flash.events.Event;
import fl.motion.MotionEvent;
import flash.net.URLVariables;
import flash.display.MovieClip;
import flashx.textLayout.elements.Configuration;
var ctr:int = 0;
var now:Date = new Date();
var myurl:String = "http://localhost:8888/eventspictures/getdata.php";
var scriptLoader:URLLoader = new URLLoader();
var scriptRequest:URLRequest = new URLRequest();
var newContainer:MovieClip;
scriptRequest.url = myurl + "?ck=" + now.getTime();
scriptLoader.addEventListener(Event.COMPLETE, handleLoadSuccess);
scriptLoader.addEventListener(IOErrorEvent.IO_ERROR, handleError);
scriptRequest.method = URLRequestMethod.POST;
scriptLoader.load(scriptRequest);
function handleLoadSuccess(evt:Event):void
{
for (var j:Number = 0; j <4; j++)
{
var newContainer:MovieClip = new con();
newContainer.name = String(ctr);
newContainer.y = j*80 +65;
newContainer.x= 16;
stage.addChild(newContainer);
var variables:URLVariables = new URLVariables(evt.target.data);
trace(variables.output);
var parse:String = variables.output;
var parsed:Array = parse.split("<|>");
var tab:String = ' ';
var eventname:String = '';
var date:String='';
var slotsleft:String='';
// different variable names to assign to different column names(etc; eventname, date, slotsleft)
// loop through.. start from O
for (var i:Number = 0; i<parsed.length-1; i++)
{
trace(parsed[i]);
var item:String = parsed[i];
var itemarray:Array = item.split(",");
eventname += itemarray[2] + tab + "<br>";
date += itemarray[3] + tab;
slotsleft += itemarray[4] + tab;
trace(eventname);
newContainer.eventname_txt.htmlText = eventname;
newContainer.date_txt.htmlText= date;
newContainer.slotsleft_txt.htmlText=slotsleft;
}
}
//slotsleft_txt.x = 270;
}
function handleError(evt:IOErrorEvent):void
{
}
backbutton_mc.addEventListener(MouseEvent.CLICK, goHomePage);
function goHomePage (evt:Event):void{
gotoAndPlay("dashboard");
removeChild(newContainer);
}
stop();

In your function handleLoadSuccess() you have a loop that creates 4 MovieClip's and adds them to the stage.
But in your goHomePage() function you only try to remove one object from the stage. It turns out this object is probably null in your example (trying to remove an object that is null should generate an error if you are using the debug Flash player).
The reason it is probably null is because you have defined two variables named newContainer in your code: one is declared at the beginning of the script, and the second one inside the function handleLoadSuccess() (because you are using the keyword var on each line).
The variable created inside the function only exists while that function is executing. The variable created outside the function never seems to receive a value.
Two approaches you can use:
Keep track of the things you add to the stage, by putting them in an Array:
Replace the newContainer variable that is outside the function with an Array called containers:
var containers:Array = [];
In the function handleLoadSuccess(), when you add each MovieClip to the stage, also add them to the containers array:
stage.addChild(newContainer);
containers.push(newContainer);
Finally in the function goHomePage() iterate over the containers array to remove each MovieClip:
for (var j:int = 0; j < containers.length; j++)
{
stage.removeChild( containers[j] );
}
// reset the containers array so it's empty for the next time
// and to remove the references to the MovieClips (to prevent a memory leak)
containers=[];
Blindly remove everything from the stage
If this is accetpable, it is much easier. Just iterate backwards over the children of the stage in your goHomePage() function:
for (var j:int = stage.numChildren; j >= 1; j--)
{
stage.removeChildAt(j - 1);
}

Related

Actionscript: get textfields and assign them dynamically

I'm trying to create a highscore list.
I have a movieclip ("highscore") and in it i have dynamic textfields with instance names. Now i'm trying to get those textfields so that i can change the text inside. Since i'm getting them in a loop i get them with getChildByName (and this works). But what i get back is a displayObject and therefore i get the error: implicit coercion of a value of type class to an unrelated type...
I know what the error is.. but i have no idea how to fix it.
Here is my code:
private function updateSingleList(result:XML):void
{
if(result['header']['success'] != 'true'){
return;
}
for(var i:uint = 0; i < result['items']['item'].length(); i++)
{
var pos:uint = i+1;
var name:String = 'name_' + pos;
var score:String = 'score_' + pos;
var rowName:TextField = highscore.getChildByName(name);
var rowScore:TextField = highscore.getChildByName(score);
rowName.text = result['items']['item'][i]['name'].toString();
rowScore.text = result['items']['item'][i]['score'].toString();
}
}
thanks!
Specify that the child you want is a TextField :
var rowName:TextField = highscore.getChildByName('name_' + pos) as TextField;
rowName.text = result['items']['item'][i]['name'].toString();

addCircle to existing movieclip, using name of clip from an array

I am currently building a project where I have a map with a number of ship and aircraft. What I am trying to achieve is to check the Line of Sight distance between them.
I have set up a LOS Calculator which checks the height of one platform and the height of a second platform then gives a response. That works fine.
I then wanted to addCircle based on the result from this calculator. So if the result was 10 it would draw a circle 10cm in radius. If the result was 100 then it would draw it at 100, you get the picture. This works.
My problem now is that I need to be able to click on one platform either before or after I have made the calculation and the .addCircle be added to that movieClip. I have set up an array to store the movieclips instance names and traced that. I have added a field on stage so that you can click on a platform and it will recognise the platform clicked. I am just lost as to how to get the circle into the movieClip that has been clicked.
I am very new to AS3 so this is starting todo my head in. Any help would be greatly appreciated.
The code I have is attached below. I hope I have inserted this properly. Thanks again
import flash.events.MouseEvent;
import flash.display.MovieClip;
stage.focus=ht1;
// creation of array containing movieclips and code that adds the clicked movieclip to Array-platformClicked
var platformArray:Array = [arunta_mc, f15_mc];
var platformClicked = [];
var selectedPlatform:MovieClip = new MovieClip();
for(var i:int = 0; i < platformArray.length; i++) {
platformArray[i].buttonMode = true;
platformArray[i].addEventListener(MouseEvent.CLICK, item_onClick);
}
function item_onClick(event:MouseEvent):void {
var selectedPlatformArray:Array = platformArray.filter(checkName);
selectedPlatform = selectedPlatformArray[0];
myText.text = event.currentTarget.name + " was clicked";
var platformClicked = String(event.currentTarget.name);
trace(platformClicked);
}
function checkName(item:MovieClip, index:int, array:Array):Boolean
{
return(item.name == platformClicked);
}
//setup of LOS Calculator code
var counter:Number=1;
operator_txt.text = "+";
ht1.restrict="-0123456789.";
ht2.restrict="-0123456789.";
var myresult:Number;
var test = [];
//start of code when equal button is pressed
equal_btn.addEventListener(MouseEvent.CLICK, equalhandler);
var newCircle:Shape = new Shape();//defines circle to be drawn
function equalhandler(event:MouseEvent):void{
newCircle.graphics.lineStyle(1, 0x000000);
newCircle.graphics.beginFill(0x435632);
newCircle.alpha = .1;
//start of result code
result_txt.text = String(int((1.23*(Math.sqrt(Number(parseFloat(ht1.text)+parseFloat(ht2.text)+""))))));
var test = String(int((1.23*(Math.sqrt(Number(parseFloat(ht1.text)+parseFloat(ht2.text)+""))))));
trace(test);
//end of result code
newCircle.graphics.drawCircle(0,0,test);//add circle based on LOS calculation
newCircle.graphics.endFill();
//var selectedPlatform:MovieClip = selectedPlatformArray[0];
selectedPlatform.addChild(newCircle);//this is where I need to add newCircle to the movieClip that is clicked
trace(selectedPlatform);
//trace(platformClicked);
}
//start of code for the clear button
clear_btn.addEventListener(MouseEvent.CLICK, clearhandler);
function clearhandler(event:MouseEvent):void{
ht1.text=ht2.text=result_txt.text="";
removeChild(newCircle);
var test = [];
}
You can use the filter() method to check each item's name, like so:
var selectedPlatformArray:Array = platformArray.filter(checkName);
and somewhere in your code, define the checkName function
function checkName(item:MovieClip, index:int, array:Array):Boolean
{
return (item.name == platformClicked);
}
selectedPlatformArray will now contain all elements that return true for the checkName function, and as long as you don't have multiple MovieClips with the same name the array should only contain one element, which you can retrieve simply by accessing the first element of the array:
var selectedPlatform:MovieClip = selectedPlatformArray[0];
Alternatively, you can also use the getChildByName() function, like so:
var selectedPlatform:MovieClip = stage.getChildByName(platformClicked);
However this depends on where the objects are added to, and if they're not all in the same container (or not added at all), then this isn't the best option. It's a quick and simple solution for small projects though.
Anyway, whatever method you use you can then easily add the circle to it in your equalHandler function as usual:
selectedPlatform.addChild(newCircle);
I'd recommend checking out the documentation for both filter() and getChildByName(), to get a better understanding of how they work, since my examples only showed how you'd use them in this specific situation.
Complete code that you should have:
import flash.events.MouseEvent;
import flash.display.MovieClip;
stage.focus=ht1;
// creation of array containing movieclips and code that adds the clicked movieclip to Array-platformClicked
var platformArray:Array = [arunta_mc, f15_mc];
var platformClicked:String = "";
var selectedPlatform:MovieClip = new MovieClip();
for(var i:int = 0; i < platformArray.length; i++) {
platformArray[i].buttonMode = true;
platformArray[i].addEventListener(MouseEvent.CLICK, item_onClick);
}
function item_onClick(event:MouseEvent):void {
var selectedPlatformArray:Array = platformArray.filter(checkName);
selectedPlatform = selectedPlatformArray[0];
myText.text = event.currentTarget.name + " was clicked";
platformClicked = String(event.currentTarget.name);
trace(platformClicked);
}
function checkName(item:MovieClip, index:int, array:Array):Boolean
{
return(item.name == platformClicked);
}
//setup of LOS Calculator code
var counter:Number=1;
operator_txt.text = "+";
ht1.restrict="-0123456789.";
ht2.restrict="-0123456789.";
var myresult:Number;
var test:String = "";
//start of code when equal button is pressed
equal_btn.addEventListener(MouseEvent.CLICK, equalhandler);
var newCircle:Shape = new Shape();//defines circle to be drawn
function equalhandler(event:MouseEvent):void{
newCircle.graphics.lineStyle(1, 0x000000);
newCircle.graphics.beginFill(0x435632);
newCircle.alpha = .1;
//start of result code
result_txt.text = String(int((1.23*(Math.sqrt(Number(parseFloat(ht1.text)+parseFloat(ht2.text)+""))))));
test = String(int((1.23*(Math.sqrt(Number(parseFloat(ht1.text)+parseFloat(ht2.text)+""))))));
trace(test);
//end of result code
newCircle.graphics.drawCircle(0,0,test);//add circle based on LOS calculation
newCircle.graphics.endFill();
//var selectedPlatform:MovieClip = selectedPlatformArray[0];
selectedPlatform.addChild(newCircle);//this is where I need to add newCircle to the movieClip that is clicked
trace(selectedPlatform);
//trace(platformClicked);
}
//start of code for the clear button
clear_btn.addEventListener(MouseEvent.CLICK, clearhandler);
function clearhandler(event:MouseEvent):void{
ht1.text=ht2.text=result_txt.text="";
selectedPlatform.removeChild(newCircle);
test = "";
}

How to create a series of class instances in a for loop, as3

In my library I have a bunch of classes named tip1, tip2, tip3, tip4...and so on. Is it possible to create one instance of each on the stage using a for loop? I tried this but it didn't seem to work.
var tips:int = 12;
for(var i:int = 1; i<=tips; i++){
var tipName:String = "tip"+i
var tip:MovieClip = new tipName();
tip.name = "tip" + i
tip.x = stage.width;
tip.y = 0;
addChild(tip);
}
Any help would be appreciated. Thanks!
You were missing the "getDefinitionByName" part.
// Up top
import flash.utils.getDefinitionByName;
// Down below
var tips:int = 12;
for (var i:int = 1; i < tips; ++i ) {
var myClass:Class = getDefinitionByName('tip' + i) as Class;
var tip:Object = new myClass();
tip.name = "tip" + i;
....
}
Instead of
var tip:MovieClip = new tipName();
Try (written from memory)
var clazz:Class = getDefinitionByName(tipName) as Class;
var tip:MovieClip = new clazz();
Also, you generally want to use stage.stageWidth instead of stage.width, since the latter will return the stage bounding box width (which might not be the same as the area the swf file covers).

Multiple movieclips all go to the same spot; What am i doing wrong?

So I'm trying to shoot multiple bullets out of my body and it all works except I have an odd problem of just one bullet showing up and updating to set position for the new ones.
I have a move able player thats supposed to shoot and I test this code by moving the player and shooting. Im taking it step by step in creating this.
The result of tracing the bulletContainer counts correctly in that its telling me that movieclips ARE being added to the stage; I Just know it comes down to some kind of logic that im forgetting.
Here's My Code (The Bullet it self is a class)
UPDATE*
Everything in this code works fine except for I stated earlier some code seems reduntned because I've resorted to a different approaches.
BulletGod Class:
public class bulletGod extends MovieClip{
//Register Variables
//~Global
var globalPath = "http://127.0.0.1/fleshvirusv3/serverside/"
//~MovieCLips
var newBullet:bulletClass = new bulletClass();
//~Boolean
var loadingBulletInProgress:Number = 0;
var shootingWeapon:Number = 0;
//~Timers
var fireBulletsInterval = setInterval(fireBullets, 1);
var bulletFireEvent;
//~Arrays
var bulletArray:Array = new Array();
var bulletType:Array = new Array();
var bulletContainer:Array = new Array();
//~Networking
var netBulletRequest:URLRequest = new URLRequest(globalPath+"bullets.php");
var netBulletVariables:URLVariables = new URLVariables();
var netBulletLoader:URLLoader = new URLLoader();
//~Bullet Image Loader
var mLoader:Loader = new Loader();
var mRequest:URLRequest = new URLRequest();
public function bulletGod() {
//Load every bullet for every gun
//Compile data to be requested
netBulletVariables.act = "loadBullets"
netBulletRequest.method = URLRequestMethod.POST
netBulletRequest.data = netBulletVariables;
netBulletLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
netBulletLoader.addEventListener(Event.COMPLETE, getBulletImages);
netBulletLoader.load(netBulletRequest);
}
private function getBulletImages(bulletImageData:Event){
//Request every bullet URL image
//Set vars
var bulletData = bulletImageData.target.data;
//Load images
for(var i:Number = 0; i < bulletData.numBullets; i++){
bulletArray.push(bulletData["id"+i.toString()]);
bulletType.push(bulletData["bullet"+i.toString()]);
//trace(bulletData["id"+i]+"-"+bulletData["bullet"+i]);
}
//All the arrays have been set start firing the image loader/replacer
var imageLoaderInterval = setInterval(imageReplacer, 10);
}
private function imageReplacer(){
//Check to see which image needs replacing
if(!loadingBulletInProgress){
//Begin loading the next image
//Search for the next "String" in the bulletType:Array, and replace it with an image
for(var i:Number = 0; i < bulletType.length; i++){
if(getQualifiedClassName(bulletType[i]) == "String"){
//Load this image
mRequest = new URLRequest(globalPath+"ammo/"+bulletType[i]);
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadImage);
mLoader.load(mRequest);
//Stop imageReplacer() while we load image
loadingBulletInProgress = 1;
//Stop this for() loop while we load image
i = 999;
}
}
}
}
private function loadImage(BlackHole:Event){
//Image has loaded; find which array slot it needs to go into
for(var i:Number = 0; i <= bulletType.length; i++){
if(getQualifiedClassName(bulletType[i]) == "String"){
//We found which array type it belongs to; now replace the text/url location with the actual image data
var tmpNewBullet:MovieClip = new MovieClip;
tmpNewBullet.addChild(mLoader);
//Add image to array
bulletType[i] = tmpNewBullet;
//Restart loadingBullets if there are more left
loadingBulletInProgress = 0;
//Stop for() loop
i = 999;
}
}
}
//###############################################################################################################################################
private function fireBullets(){
//If player is holding down mouse; Fire weapon at rate of fire.
if(shootingWeapon >= 1){
if(bulletFireEvent == null){
//Start shooting bullets
bulletFireEvent = setInterval(allowShooting, 500);
}
}
if(shootingWeapon == 0){
//The user is not shooting so stop all bullets from firing
if(bulletFireEvent != null){
//Strop firing bullets
clearInterval(bulletFireEvent);
bulletFireEvent = null
}
}
}
private function allowShooting(){
//This function actually adds the bullets on screen
//Search for correct bullet/ammo image to attach
var bulletId:Number = 0;
for(var i:Number = 0; i < bulletArray.length; i++){
if(bulletArray[i] == shootingWeapon){
//Bullet found
bulletId = i;
//End For() loop
i = 999;
}
}
//Create new bullet
//Create Tmp Bullet
var tmpBulletId:MovieClip = new MovieClip
tmpBulletId.addChild(newBullet);
tmpBulletId.addChild(bulletType[bulletId]);
//Add To Stage
addChild(tmpBulletId)
bulletContainer.push(tmpBulletId); //Add to array of bullets
//Orientate this bullet from players body
var bulletTmpId:Number = bulletContainer.length
bulletTmpId--;
bulletContainer[bulletTmpId].x = Object(root).localSurvivor.x
bulletContainer[bulletTmpId].y = Object(root).localSurvivor.y
//addChild(bulletContainer[bulletTmpId]);
}
//_______________EXTERNAL EVENTS_______________________
public function fireBullet(weaponId:Number){
shootingWeapon = weaponId;
}
public function stopFireBullets(){
shootingWeapon = 0;
}
}
}
BulletClass:
package com{
import flash.display.*
import flash.utils.*
import flash.net.*
import flash.events.*
public class bulletClass extends MovieClip {
public var damage:Number = 0;
public function bulletClass() {
//SOME MOVEMENT CODE HERE
}
public function addAvatar(Obj:MovieClip){
this.addChild(Obj);
}
}
}
Well ... if I may say so, this code looks quite wrong. Either something is missing from the code or this code will never make the bullets fly.
First off, you can set x and y of the new bullet directly (replace everything after "orientate this bullet from players body" with this):
tmpBulletId.x = Object(root).localSurvivor.x;
tmpBulletId.y = Object(root).localSurvivor.y;
Perhaps this already helps, but your code there should already do the same.
But to let these bullets fly into any direction, you also need to add an event listener, like so:
tmpBulletId.addEventListener(Event.ENTER_FRAME, moveBullet);
function moveBullet(e:Event) {
var movedBullet:MovieClip = MovieClip(e.currentTarget);
if (movedBullet.x < 0 || movedBullet.x > movedBullet.stage.width ||
movedBullet.y < 0 || movedBullet.y > movedBullet.stage.height) {
// remove move listener, because the bullet moved out of stage
movedBullet.removeEventListener(Event.ENTER_FRAME);
}
// remove the comment (the //) from the line that you need
MovieClip(e.currentTarget).x += 1; // move right
// MovieClip(e.currentTarget).y -= 1; // move up
// MovieClip(e.currentTarget).x -= 1; // move left
// MovieClip(e.currentTarget).y += 1; // move down
}
This example lets your bullet fly to the right. If you need it flying into another direction, just comment out the line with the "move right" comment and uncomment one of the other lines.
This is of course a very simple example, but it should get you started.
I hope this helps, and that my answer is not the wrong answer to the question.
As far as I have expirienced it you can have only one copy of MovieClip object added to specific child. Best approach is to use ByteArray for the clip source and instantiate new MovieClip and pass the ByteArray as a source. It have something to do with child/parent relation since a DisplayObject can have only one parent (and a way to detach the object from scene too).
Well i ended up writeing the whole code from scratch for a 3rd time and ran into a similar problem and just for reference to anybody else that comes to a problem thats random as this one i found that problem was likly does to a conversion error somewhere that doesn't necessarily break any compiling rules. Just that i was calling a movieclip and not the class it self.

How to pass a variable into an Event.COMPLETE function?

I am running a loop to pull thumbs into a containing movieclip from an xml list. What I want to do is have the thumb's parent movieclip fade in after they are done loading, but I can't figure out how to reference the parent once it's loaded.
My code(which currently doesn't work the way I want it):
var vsThumb:articleBox;
var currentarticleX:Number = 0;
var articleLinkURL:String;
var articleImageURL:String;
var articleText:String;
var vsThumbLoader:Loader;
var next_x:Number;
next_x = 9;
var thumbAlphaTween:Tween;
var articlevsThumb:Array = new Array();
function loadarticleHeadlines():void
{
for (var i:int = 0; i < egarticleXml.articlelist.articleitem.length(); i++)
{
vsThumb = new articleBox();
vsThumb.alpha = 0;
vsThumbLoader = new Loader();
vsThumbLoader.load(new URLRequest(egarticleXml.articlelist.articleitem[i].articlethumbnail));
articleListContainter.addChild(vsThumb);
vsThumb.articleImage.addChild(vsThumbLoader);
vsThumb.articleTitle.text = egarticleXml.articlelist.articleitem[i].articletitle;
titleAutosize(vsThumb.articleTitle);
vsThumb.x = next_x;
next_x += 260;
articlevsThumb[i] = vsThumb;
vsThumbLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, showBox);
vsThumb.clickBtn.buttonMode = true;
}
function showBox(event:Event):void
{
thumbAlphaTween = new Tween(articlevsThumb[i],"alpha",None.easeNone,0,1,.25,true);
}
}
So how do I refer back to the loader's parent so I can fade in the whole movieclip? Can I pass a variable into the showBox function?
Don't use nested functions. They tend to make things more complicated.
i will always have the end value (articleitem.length()-1) in all of the event handlers you create, because its scope is the outer function, loadarticleHeadlines (it will increase by 1 on every iteration). That's probably why your code doesn't work.
The event will be fired on the loaderInfo of your loader, so you can find the loader's parent by using event.target.loader.parent:
function loadarticleHeadlines() : void
{
for (var i:int = 0; i < egarticleXml.articlelist.articleitem.length(); i++)
{
vsThumb = new articleBox();
vsThumb.alpha = 0;
vsThumbLoader = new Loader();
vsThumbLoader.load(new URLRequest(egarticleXml.articlelist.articleitem[i].articlethumbnail));
articleListContainter.addChild(vsThumb);
vsThumb.articleImage.addChild(vsThumbLoader);
vsThumb.articleTitle.text = egarticleXml.articlelist.articleitem[i].articletitle;
titleAutosize(vsThumb.articleTitle);
vsThumb.x = next_x;
next_x += 260;
articlevsThumb[i] = vsThumb;
vsThumbLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, showBox);
vsThumb.clickBtn.buttonMode = true;
}
}
function showBox(event:Event):void
{
thumbAlphaTween = new Tween(event.target.loader.parent,"alpha",None.easeNone,0,1,.25,true);
}
You don't need to pass a variable to your showBox, use the target property of the Event to retrieve the Loader:
function showBox(event:Event):void
{
var li:LoaderInfo=LoaderInfo(event.target);
// be nice remove your listener when your are done
li.removeEventListener(Event.COMPLETE, showBox);
var ldr:Loader=li.loader; // here is your loader
// do whatever you want with loader
thumbAlphaTween = new Tween(articlevsThumb[i],"alpha",None.easeNone,0,1,.25,true);
}