Array of movie clips ActionScript 3 - arrays

How would I go about making an array of movie clips?
If you could include an example with the setting of one part of the array, that would be great :)

(untested code)
//Create array of movie clips
var someArray:Array = new Array(mc1,mc2,mc3,mc4);
//Access certain movie clip, in this case mc3
someArray[2].visible = false;
Also consider using a vector, it is generally faster.
//Declare a vector
var someVector:Vector.<MovieClip> = new Vector.<MovieClip>();
//Add movie clips
someVector.push(mc1);
someVector.push(mc2);
someVector.push(mc3);
someVector.push(mc4);
To access them I would do it like this:
var tempMC:MovieClip = someArray[1]; // or = someVector[1];
tempMC.x = 30;
tempMC.width = 300;
or you can just say:
MovieClip(someArray[1]).x = 30;
or the lazy way as shown on the 2nd line of code above.

Related

In Actionscript 3, how to create many instances of the same symbol?

Though coding, I must make many copies of the same MovieClip to be placed on the stage, each to be manipulated code-wise on its own
For instance, I have a MovieClip named MC and I wish to have 99 copies of ít loaded onto the stage, each in a different x coordinate. What should I do?
I think on doing this:
Step 1: in the library, turning MC into a class
Step 2: placing the following code in the scene's script
var MyArray:Array = new Array
for (var i:int = 0; i<99;i++)
{
var MCInstance:MC = new MC
MC Instance = MyArray[i]
MovieClip.(MyArray[i]).x = i*30
}
Would that make sense?
That's probably the right idea, your syntax is just a little off. Try this:
var myArray:Array = [];
for (var i:int = 0; i < 99;i++)
{
var mc:MC = new MC();
myArray[i] = mc;
mc.x = i * 30
}
AS3 style conventions: use lowerCamelCase for variable names, don't omit constructor parens even though they are optional, and create arrays using literals (source).
You could push each MovieClip to an Array after adding it to the Stage.
var myArray = [];
for(var i:int = 0; i < 99; i++)
{
var myMc:MC = new MC();
addChild(myMc);
myMc.x = myMc.width * i + 2;
myMc.y = 10;
myArray.push(myMc);
}

Actionscript 3 and sorting incoming bytes from an arduino

im new to using action script so i apologies if this wont make sense, the issue iam having is that the incoming bytes from my arduino are not being stored properly in an array. The bytes come in one at a time from my arduino and will be stored in an array in as3.
i have two values SF-F8-001, SF-F8-002 and SF-F8-003 etc... when i trace the incoming bytes i get this:
S
F
-
F
8
-
0
0
1
so when i look at that i realized i needed an array to store the byte as they come in however i have tried many different things but it hasnt worked
however this code below seems to get me close to my desired result
import flash.events.*;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequestMethod;
var ary:Array = new Array();
var bar_grab:Array = new Array();
var array:Array = new Array();
trace("__AS3 Example__");
var socket:Socket = new Socket("localhost",5331);
socket.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
function socketDataHandler(event:ProgressEvent):void
{
var str:String = String(socket.readUTFBytes(socket.bytesAvailable));
var b:String;
bar_grab.push(str);
b = bar_grab.join("");
boxtwo.text = b;
}
this code gets me this
SF-F8-001SF-F8-002SF-F8-003 etc...
however the result iam looking for is this
SF-F8-001,SF-F8-002,SF-F8-003 etc....
so if anyone could help me sort this out i will be grateful
thank you
If you know a priori how many characters each item will consist of you could read everything to string and get each individual item like that:
//Main string containing all items
var allString:String = "123456789";
//Number of chars in of item
var charsInItem = 3;
var item:String;
var index:int;
var resultArray:Array = new Array();
for(var i:int = 0; i < allString.length/charsInItem; i++)
{
index= i*charsInItem;
//traces name of one item
item = allString.slice(index, index+charsInItem);
resultArray.push(item);
trace(item);
}
//Output:
//123
//456
//789
If you don't know a number of chars in one item or it varies, I would suggest tweaking Arduino code and putting some sort of a marker in between every item. Like say a comma (,). Then your string would look something like this: "item1,item2,longerItem3". And you could split that string into array like that:
var array:Array = new Array();
var allString:String = "item1,item2,longerItem3";
//This splts string into array items using comma (,) as a seperator
array = allString.split(",");
for(var i:int = 0; i < array.length; i++)
{
//trace every array element
trace(array[i]);
}
//Output:
//item1
//item2
//longerItem3
I should add that even if you know a number of chars in one item I would still suggest using method nr.2.

Array not resetting in Game

Hey guys so i am developing a Game and i have an Array that keeps track of my 5 movie clips that are added to the stage by the array. I have a Player movie clip as well so the Player movie clip is Hittesting with all the 5 diamond movie clips which are added to the stage like so:
private var nPoints:Number = 5;..........
public function addPointsToStage():void
{
for (var i = 0; i < nPoints; i++)
{
trace(aPointsArray.length);
points = new mcGainPoints();
stage.addChild(points);
points.x = startPoint.x + (xSpacing * i);
points.y = startPoint.y - (ySpacing * i);
aPointsArray.push(points);
}
}
Now when the Player comes in contact with all the 5 movie clips everything works fine and the output for the array looks like this:
0
1
2
3
4
Then it continues to the next level.
But say that my Player doesnt hit any of the 5 movie clips or only hits a couple of them, when the next level is started the output looks like this:
5
6
7
8
9
and when the next level is started weird things start happening like points start adding to the highscore by themselves.
I think the problem is that im not destroying the array holding the 5 movie clips correctly this is the code i use to start the next level and destroy the array:
if(player.hitTestObject(mcGoal_1))
{
//Remove all points from array/stage
for (var i:int = 0; i < aPointsArray.length; i++)
{
if (aPointsArray[i].parent)
{
parent.removeChild(aPointsArray[i]);
}
startNextLevel();
}
The mcGoal_1 is the object of the game so if the player hits the goal_1 then destroy all array objects on screen and start next level. This is the startnextlevel function.
private function startNextLevel():void
{
//add points to next stage
addPointsToStage();
}
So can you see why when the next level starts the array isnt reset back to 01234? I think thats why the game has that bug of randomly adding points. Please any help will be appreciated
//Remove all points from array/stage
for (var i:int = 0; i < aPointsArray.length; i++)
if (aPointsArray[i].parent)
parent.removeChild(aPointsArray[i]);
// just one statement, no braces
aPointsArray.length=0; // clear the array itself, not just
// points from display list!
startNextLevel(); // now start level
An incorrect order of correct statements leads to a disaster. Always check your code flow, what executes now and what then, and how many times.
It doesn't look like you're removing anything from the array.
You can use a combination of .indexOf() and .splice() to remove items from an array:
function removeMc(clip:MovieClip):void
{
if(clip.parent) clip.parent.removeChild(clip);
// Also remove from array.
var index:int = aPointsArray.indexOf(clip);
aPointsArray.splice(index, 1);
}
It might also be worth simply emptying the array when you startNextLevel():
private function startNextLevel():void
{
aPointsArray.length = 0;
//add points to next stage
addPointsToStage();
}
Just assign your array to null value. so that array will start from begining whenever you require. i hope the following code code would helps you.
var nPoints:Number = 5;
var points:poin;
var aPointsArray:Array;
var startPoint:Number = 0;
var xSpacing:Number = 20;
var ySpacing:Number = 20;
addPointsToStage();
function addPointsToStage():void
{
aPointsArray = null;
aPointsArray = new Array();
for (var i:int = 0; i < 6; i++)
{
trace(aPointsArray.length);
points = new poin();
addChild(points);
points.x = 100+ (xSpacing * i);
points.y = 200 - (ySpacing * i);
aPointsArray.push(points);
}
}

AS3 : AddChild based on Array Value

Let's say I have an array, each item in the array has a corresponding library item.
I'd like to do something like :
var rando = Math.round(Math.random()*3)
var myArray = new Array ["ball", "wall", "fall"]
var i:myArray[rando] = myArray[rando] new myArray[rando]()
addChild(i)
But, this doesn't work. What's the secret?
Thank You,
Victor Hugo
Surprised no one mentioned getDefinitionByName() here.
Here's some complete code to get your example working:
var myArray = ["ball", "wall", "fall"];
/**
* Creates a random instance based on an input array containing class names as Strings.
* #param The input array containing aforementioned Strings.
* #return The newly created instance.
*/
function createRandom(typeArray:Array):*
{
// Select random String from typeArray.
var selection:String = typeArray[ int(Math.random() * typeArray.length) ];
// Create instance of relevant class.
var Type:Class = getDefinitionByName(selection) as Class;
// Return created instance.
return new Type();
}
// Randomly create and add instance.
var instance:DisplayObject = createRandom(myArray);
addChild(instance);
Ok so there are a bunch of problems with this.
A large one being var i:myArray[rando] = myArray[rando] new myArray[rando]() not really too sure what you're trying to do here.
Anyway I'm going to assume ball, wall and fall are instance names of MovieClips you have in your library. I think you're going to want something like this
var rando:int = Math.floor(Math.random()*3); //As the comments point out this should give you a random
//int between 0 and 2, arrays are 0 indexed so this is what we want if we have 3 items
Now for your array, you're current putting strings in there. Flash has no idea what "ball", etc are.
Try something like this
var myArray:Array = new Array [new ball(), new wall(), new fall()]; //this creates a new instance of your library object and stores it in your array
Now to add one of these to your stage:
addChild(myArray[rando]); //this uses the random number to pull one of the items out of your array
What you're trying to do with var i:myArray[rando] doesn't really make sense. There is no type of myArray[rando] this slot should be holding a MovieClip
If you only have a few choices, it's easier to use a switch-case.
switch (rando) {
case 0:
i = new ball();
break;
case 1:
i = new wall();
break;
case 2:
i = new fall();
break;
}
addChild(i);
I suggest you define the variable i as a MovieClip, in which case it can be instantiated as both ball, wall, fall.
Given that ball, wall and fall are in the library exported to actionscript.
Just guessing off your limited information but give this a shot.
private function myFunction():void{
var rando = Math.round(Math.random()*3);
var myArray= new Array ["ball", "wall", "fall"];
}
private function generateItem(item:String):void{
switch(item){
case "ball" : generateBall(); break;
case "wall" : generateWall(); break;
case "fall" : generateFall(); break;
}
private function generateBall():void{
//code to generate ball
addChild(ball);
}
private function generateFall():void{
//code to generate fall
addChild(fall);
}
private function generateWall():void{
//code to generate wall
addChild(wall);
}
Change your arrary line to:
var myArray = new Array [ball, wall, fall];
This should work. :)
Marty Wallace gets big praise for steering me down the path of getDefinitionByName(). The example he posted was good, but this example does exactly what I was going for.
http://www.emanueleferonato.com/2011/03/31/understanding-as3-getdefinitionbyname-for-all-eval-maniacs/

Sorting a Flex Array

I have created an array as shown below
protected function getMyArray(dataArray:Array):Array
{
var labelList:Array=new Array;
for each (var property:Object in dataArray)
{
if (labelList[property.bucketTime] != property.bucketTime)
labelList[property.bucketTime]=property.bucketTime;
}
return labelList;
}
Is it possible to sort the array labelList based on property.bucketTime?
Edit: Sample input dataArray will be like this :
var tempObj:Object = new Object;
tempObj.bucketTime = DateField.stringToDate("30-01-2010", "DD-MM-YYYY").time;
tempObj.score = 76;
dataArray.addItem(tempObj);
tempObj = new Object;
tempObj.bucketTime = DateField.stringToDate("13-02-2010", "DD-MM-YYYY").time;
tempObj.score = 21;
dataArray.addItem(tempObj);
tempObj = new Object;
tempObj.bucketTime = DateField.stringToDate("30-03-2010", "DD-MM-YYYY").time;
tempObj.score = 10;
tempArry.addItem(tempObj);
Unless bucketTime is a number; then you aren't actually populating the array. You're just adding properties to the Array Object, almost like it were a Dictionary. I've seen a Dictionary called Associative Array's and Structures in other languages.
If that is the case, an you're using the Array class as a dictionary, then there is no way to sort it. The very nature of such a structure is that they are not sortable.
However, if property.bucketTime is a number, and you are trying adding items to the array as if they were an array, you can sort using the Array.sort or Array.sortOn methods.
Atlast I sorted the labelList Array.Please find my solution below. Let me know if there is any better way to achieve this.
var termObject:Object = ObjectUtil.getClassInfo(labelList);
var termsArray:Array = termObject.properties;
var sortedColumnArray:Array = new Array;
for each(var term:Object in termsArray){
if(labelList.hasOwnProperty(term)){
sortedColumnArray.push(labelList[term]);
}
}

Resources