How to clone an object in as3 - actionscript-3

I'm quite new to as3, but the game I'm making requires the use ofclones. How would I make them (I know it involves using the child thing but I don't know how to make them)? I also need to make a function that sets their location to random places on screen, how would I do this? I'm not sure how i would refer to the clone's x and y locations without it moving all 50 of them.
Thanks

The best way to make clones of anything is to assign AS3 class to the Library item (lets say you named the class SomeThing) and then instantiate it with the new operator and add to display list with addChild(...) method.
import SomeThing;
// Lets create a list to keep things.
var things:Vector.<SomeThing> = new Vector.<SomeThing>;
function addThing():SomeThing
{
// Create.
var result:SomeThing = new SomeThing;
// Put it to a list for further reference.
things.push(result);
// Add it to display list.
addChild(result);
return result;
}
// Create one thing.
// This one will go to (0,0) coordinates.
addThing();
// You can create several things.
for (var i:int = 0; i < 100; i++)
{
var aThing:SomeThing = addThing();
aThing.x = 100 + 200 * Math.random();
aThing.y = 100 + 100 * Math.random();
}
// Now you can address things via list access.
things[49].x = 50;
things[49].y = 50;

Related

AS3: Adding function to population loop

Basically I have 2 movieclip objects with some code, currently just to trace them. The blue circles when clicked will say 'Blue' and the red ones when clicked will say 'Red'. This works fine in theory until I add a population loop, which adds more of them. Then only 1 of each colour correctly works, the rest are just 'mock' circles. I wish for each circle to tell me their colour.
This is my code for the .fla:
import flash.events.MouseEvent;
BlueBall.addEventListener(MouseEvent.CLICK, fun1)
function fun1(e:MouseEvent){
trace("Blue!");
}
RedBall.addEventListener(MouseEvent.CLICK, fun2)
function fun2(e:MouseEvent){
trace("Red!");
}
and this is the population loop in an .as file:
private function PopulateCircles():void
{
for (var i:int=0; i < 10; i++)
{
var blueCircle:BlueCircle = new BlueCircle();
this.addChild(blueCircle);
var redCircle:RedCircle = new RedCircle();
this.addChild(redCircle);
}
}
tldr; how do I get the on-click events to occur on every newly populated circle?
Pretty easy, actually. Just as you subscribe method to listen the predesigned instances' events, you can subscribe via temporary variable references. As long, as the variable holds the reference (or a pointer in C++ terms), you can address the instance and do anything you could do to a predesigned MovieClip:
private function PopulateCircles():void
{
var aRed:RedCircle;
var aBlu:BlueCircle;
for (var i:int = 0; i < 10; i++)
{
// If there are no mandatory constructor arguments,
// you can omit the () brackets.
aRed = new RedCircle;
aBlu = new BlueCircle;
// Disperse clips to random places.
aBlu.x = 500 * Math.random();
aBlu.y = 500 * Math.random();
aRed.x = 500 * Math.random();
aRed.y = 500 * Math.random();
// Subscribe methods to newly created instances.
aRed.addEventListener(MouseEvent.CLICK, fun2);
aBlu.addEventListener(MouseEvent.CLICK, fun1);
// You're operating inside 'this' object,
// no need to explicitly point it out.
addChild(aRed);
addChild(aBlu);
}
}

AS3 - Using a For Loop to Update Multiple Points and Their Values in an Array

I'm a bit new with AS3 (but not really with coding) so please forgive my ignorance. I'm creating a small function that will be called by a Main Function to update the position of 52 Pointers that have the x and y position of multiple point objects (empty movie clips). It will also then update two global arrays with those values (one array for the x and one for the y).
The problem is, as there are 52 of them, and they will probably grow in quantity, I'd like to be able to use a FOR function to do it, but I can't seem to be able to figure it out.
I get this error: Access of undefined property _point.
Here is a piece of the code that dream about:
function happyFunc():void
{
var avpointers:int = 52;
var vpointx:Array = new Array();
var vpointy:Array = new Array();
for (aa=0; aa<vpointers; aa++)
{
vpointx[aa] = _point[aa].x;
vpointy[aa] = _point[aa].y;
}
}
And this is the code that I'm stuck with...
function reallySadFunc():void
{
_point1 = localToGlobal(new Point(point1.x,point1.y));
//...
_point52 = localToGlobal(new Point(point52.x,point1.y));
vpointx[0] = _point1.x;
vpointx[1] = _point2.x;
//...
//oh god there are 104 lines of this why do I have to suffer
}
Thank you!
If I read your question correctly, I think this is what you need:
public static const CLIP_COUNT:int = 52;
// ...
private function happyFunc(parentClip:DisplayObjectContainer):void
{
var vpointx:Vector.<Number> = new Vector.<Number>(CLIP_COUNT, true);
var vpointy:Vector.<Number> = new Vector.<Number>(CLIP_COUNT, true);
var clipPoint:Point = new Point ();
var globalPoint:Point;
for (var i:int = 0; i < CLIP_COUNT; i++)
{
var childClip:DisplayObject = parentClip.getChildByName("point" +
(i + 1).toString());
clipPoint.x = childClip.x;
clipPoint.y = childClip.y;
globalPoint = parentClip.localToGlobal(clipPoint);
vpointx[i] = globalPoint.x;
vpointy[i] = globalPoint.y;
}
// do something with vpointx and vpointy - they're local variables
// and will go out of scope unless you declare them as class members
// or somehow return them from this function.
}
This function works by taking the parent display object (the one that contains the 52 movie clips - this could be the Stage) and iterates through them by getting each movie clip by name. The code assumes that your movie clips are called point1, point2, ..., point52.
To speed up the local-to-global coordinate conversion, two Point objects are created and then reused during the for loop to avoid creating many temporary Point instances.
Instead of using Array, use Vector.<Number> - this class has better performance than Array does.

AS3 reference movieclip by .name property

Yay, another simple noobie as3 question.
How can I reference a movieclip by its ".name" ?
I tried searching for a solution, but I couldn't find anything. Basically I have a set of movieclips added to the stage using a loop, so the way I found to diferentiate them was by giving them a .name of "something" + the Loop's "i". So now they are named something like "something1", "something2", "something3", and so on.
Now, I need to send some to a specific frame. Usually I would do something like:
something1.gotoAndStop(2);
But "something1" isnt the instance name, just the ".name". I cant find a way to reference it.
you want to use getChildByName("name") more info
import flash.display.MovieClip;
// create boxes
for(var i:int = 0 ; i < 4; i++){
var box:MovieClip = new myBox(); // myBox is a symbol in the library (export for actionscript is checked and class name is myBox
box.name = "box_" + i;
box.x = i * 100;
this.addChild(box);
}
// call one of the boxes
var targetBox:MovieClip = this.getChildByName("box_2") as MovieClip;
targetBox.gotoAndStop(2);
Accessing things by name is very prone to errors. It's not a good habit to get into if you're a newbie. I think a safer way to do this would be to store references to the things you're creating in the loop, for example in an array, and reference them by their indexes.
Example:
var boxes:Array = [];
const NUM_BOXES:int = 4;
const SPACING:int = 100;
// create boxes
for(var i:int = 0 ; i < NUM_BOXES:; i++){
var box:MovieClip = new MovieClip();
// You can still do this, but only as a label, don't rely on it for finding the box later!
box.name = "box_" + i;
box.x = i * SPACING;
addChild(box);
// store the box for lookup later.
boxes.push(box); // or boxes[i] = box;
}
// talk to the third box
const RESET_FRAME:int = 2;
var targetBox:MovieClip = boxes[2] as MovieClip;
targetBox.gotoAndStop(RESET_FRAME);
Note, I've also replaced many of the loose numbers with constants and vars which will also help your compiler notice errors.
You can use the parent to get the child by name. If the parent is the stage:
var something1:MovieClip = stage.getChildByName("something1");
something1.gotoAndStop(2);

AS3 Can't access MC on Stage

I have 54 MC's on stage, generated dynamically. Now I want to get their x and y positions when rolling over but I am having problems getting the path correct e.g.
function copyFlightCellData():void {
var r; var s;
var cellData:Array = new Array ();
for (r = 0; r < 54; r++){
//var copyCellData = new MovieClip();
cellData[r] = Object(root).mc85.name; //["mc"+r+r];
trace("$$$$$$$$$$$$$$$$$$$$$" + cellData[r]);
}
}
I used the list objects in debug and they are listed in _level0 e.g.
Movie Clip: Frame=1 Target="_level0.mc85"
Not sure why I can't access their properties.
This is the code that created the MC's
// Create copies of flightCell for board grid
var my_mc = new flightCell();
my_mc.name = "mc" + i + j;
trace("^^^^^^^^^^^^^^****************" + my_mc.name);
addChild(my_mc);
Answer is pretty simple, use the DisplayObjectContainer object's, in this case root, getChildByName() method, for example:
var sprite1:Sprite = new Sprite();
sprite1.name = "sprite1";
addChild(sprite1);
trace((root as DisplayObjectContainer).getChildByName("sprite1").name); // output : sprite1
It's probably a better idea to store the movieclips you have on your stage in an array to begin with.
To access it by name you have to assign a name to them when you create them.
mc85.name = "mc85";
As an alternative that I recommend, you can use getChildAt(index) : http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html?filter_flash=cs5&filter_flashplayer=10.2&filter_air=2.6#getChildAt()
Also, I highly recomend you to create an empty movieclip or sprite and add all of this mcs to them instead of the root.

Add multiple movieclips, not replacing the old ones

So, in short, my problem is this. I am using a variable which is a movieclip loaded from an external swf. I want to "spawn" multiple instances of the movieclip that all react to the same code, so for example if I say var1.x = 100, they all are at 100x. But my problem is when I run addChild(var1) multiple times(I'm not actually typing in addChild(var1) over and over, I just have it set to add them at random times), the new child just replaces the old one, instead of making multiple movieclips. Should I do something like
var var1:MovieClip
var var2:MovieClip = new var1 ?(which doesnt work for me btw, gives me errors)
Oh, heres the code, and also, I am pretty new to as3 fyi, still don't even know how arrays work, which was my second guess to the problem.
var zombieExt:MovieClip;
var ldr2:Loader = new Loader();
ldr2.contentLoaderInfo.addEventListener(Event.COMPLETE, swfLoaded2);
ldr2.load(new URLRequest("ZombieSource.swf"));
function swfLoaded2(event:Event):void
{
zombieExt = MovieClip(ldr2.contentLoaderInfo.content);
ldr2.contentLoaderInfo.removeEventListener(Event.COMPLETE, swfLoaded2);
//zombieExt.addEventListener(Event.ENTER_FRAME, moveZombie)
zombieExt.addEventListener(Event.ENTER_FRAME,rotate2);
function rotate2 (event:Event)
{
var the2X:int = playerExt.x - zombieExt.x;
var the2Y:int = (playerExt.y - zombieExt.y) * 1;
var angle = Math.atan(the2Y/the2X)/(Math.PI/180);
if (the2X<0) {
angle += 180;
}
if (the2X>=0 && the2Y<0) {
angle += 360;
}
//angletext.text = angle;
zombieExt.rotation = (angle*1) + 90;
}
playerExt.addEventListener(Event.ENTER_FRAME,spawn1);
function spawn1 (event:Event)
{
if(playerExt.y < 417)
{
var someNum:Number = Math.round(Math.random()*20);
if(someNum == 20)
{
addChild(zombieExt)
zombieExt.x = Math.round(Math.random()*100)
zombieExt.y = Math.round(Math.random()*100)
}
}
}
}
addChild() does not create new instances. It is used to add an already created instance to the display list. If you call addChild() multiple times on the same instance then you are just readding itself.
Also each instance is unique, you can not globally change the x position of an instance by changing another one of them. What you would do is as Henry suggests and add each new instance of a MovieClip into an array, then whenever you change something you can loop through the array and apply the changes to each instance.
You can not go var2:MovieClip = new var1 either since var1 is an instance and not a class.
Here's a different method of receiving loaded MovieClips, which i use when i need many copies of the item.
in the swf you are loading, give the target movieclip a linkage name in the library, for this example i will use "foo"
private var loadedSwfClass:Class
private var newZombie:MovieClip;
private var zombieArray:Array = new Array();
function swfLoaded2(event:Event):void
{
loadedSwfClass = event.target.applicationDomain.getDefinition("foo");
for(var n:int = 0; n<100; n++){
newZombie = new loadedSwfClass()
zombieArray.push(newZombie);
addChild(newZombie);
}
}
as per this tutorial
http://darylteo.com/blog/2007/11/16/abstracting-assets-from-actionscript-in-as30-asset-libraries/
although the comments say that
var dClip:MovieClip = this;
var new_mc = new dClip.constructor();
this.addChild(new_mc);
will also work.
It sounds like you might be accessing the same instance some how in your code. It would be helpful to see your code to figure this one out.
If I wanted to load in one swf files and add a MovieClip multiple times I would place it in the library of that SWF file. And then instantiate it and store it into an object pool or a hash or some list.
// after the library were finished loading
var list:Array = [];
for(var i:int=0; i<10; i++) {
var myCreation:MySpecialThing = new MySpecialThing();
addChild(myCreation);
list.push(myCreation);
}
where my library would contain a linkage to the class MySpecialThing.
Calling addChild(var1) multiple times on the same parent doesn't have any effect (unless you have added another child to the same parent in between, in which case it will change the child index and bring var1 to the top). If you call it on different parents, it will just change the parent of var1, doesn't duplicate. Call addChild(new MovieClassName()) at random times instead to add new copies of it. Use an array as suggested here to access them later.
Wow, thanks there henry, just using an array did exactly what I needed, and made things alot simpler.
when you load in using a loader you only get 1 instance, however you can do some funky reflection to determine what class type the given loader.content is, and then instantiate them using that. For Example:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_completeHandler);
loader.load(new URLRequest("ZombieSource.swf"));
var classType:Class;
function loader_completeHandler(evt:Event):void
{
var loadInfo:LoaderInfo = (evt.target as LoaderInfo);
var loadedInstance:DisplayObject = loadInfo.content;
// getQualifiedClassName() is a top-level function, like trace()
var nameStr:String = getQualifiedClassName(loadedInstance);
if( loadInfo.applicationDomain.hasDefinition(nameStr) )
{
classType = loadInfo.applicationDomain.getDefinition(nameStr) as Class;
init();
}
else
{
//could not extract the class
}
}
function init():void
{
// to make a new instance of the ZombieMovie object, you create it
// directly from the classType variable
var i:int = 0;
while(i < 10)
{
var newZombie:DisplayObject = new classType();
// your code here
newZombie.x = stage.stageWidth * Math.random();
newZombie.x = stage.stageHeight * Math.random();
i++;
}
}
Any problems let me know, hope this helps.