Clone an instance of a class (Display Object) - actionscript-3

I have a collection of movieclips, I would like to create a clone (a new instance) of a instance everytime I create a new object.
For example
var s:Star = new Star(); // star-shaped movielcip
addChild(s);
// then I want to duplicate an instance of s and add it beside s
For an example like above, it's simple enough to create a new instance with a different name and just add it to the display list. But I have a list of objects I would like to clone as a group...?

Belowed code is very famous for cloning the objects. It's deepest and dynamic.
...
function clone(orjObj:Object):Object {
var copyObj:ByteArray = new ByteArray();
copyObj.writeObject(orjObj);
copyObj.position = 0;
return(copyObj.readObject());
}
var s2:Star = clone(s);
s2.x = s.x + s.width;
s2.y = s.y;
addChild(s2);

moses' solution is correct. What is the purpose of the clone, where you wouldn't need to know the name of the clone to reference it?
One option is you could create an array to store your references in so you don't need to explicitly name them. Using moses' code...
var clones:Array = new Array();
for each (var star:Star in [s, s2, s3, s4, s5]) {
clones.push(clone(star));
}
trace(clones.length); // 5
This will result in an array that holds 5 cloned stars. It takes the least amount of code but it's up to you to make sure you know which star is which afterwards.

Related

Use an objects name to make changes to the object

I have created multiple instances of one object each with there own instance names with numbers on the end. I would like to iterate through these names (they have numbers on the end), modify there properties then push them to an array all through the instance names not the actual object instances.
if (instance60.currentFrame == 4)
{
array.push("instance60")
}
Where the first instance60 is refering to the object itself and the second instance60 is just a pushed string
I think what you are looking to do is set a key value pair.
The key would be how you find the reference to the object later
instances["instance"+60] = instance60;
you can loop using something like:
for(var i:uint=0;i<instances.length;i++){
instances["instance"+i] = new Sprite();
instances["instance"+i].x = 20;
instances["instance"+i].y = 20*i;
//etc...
}
But, although this has it's uses, in this case you are iterating through an integer value anyways, so, given it can run quite a bit faster on large arrays, why not just store them at their position in the array?
for(var i:uint=0;i<instances.length;i++){
instances[i] = new Sprite();
instances[i].x = 20;
instances[i].y = 20*i;
this.addChild(instance[i]);
//etc...
}

Array of stagewebviews

I am in the need of multiple staged WebViews for holding multiple loaded websites at the same time.
I was hoping to manage this by making an array of webviews object, so i could call them later as view[i].
var view:Array=[webview0, webview1, webview2];
for each (var v in view){
var v:StageWebView = new StageWebView();
This gives error: 1086: Syntax error: expecting semicolon before left bracket.
Does someone know how to make an array like that?
You're doing something really weird there in terms of syntax. If you just want an Array of freshly created instances, it goes like that:
// Initialize the array.
var Views:Array = new Array;
// This loop counts 0,1,2.
for (var i:int = 0; i < 3; i++)
{
// Create a new instance.
// Yes, you can omit () with new operator if there are no arguments.
var aView:StageWebView = new StageWebView;
// Assign the new element to your array.
Views[i] = aView;
}
Or, if you need only 3 then you don't need to go algorithmic.
var Views:Array = [new StageWebView, new StageWebView, new StageWebView];
Not on topic but related:
Here is an example of one HTML page hold multiple StageWebViews
https://www.w3schools.com/graphics/tryit.asp?filename=trymap_basic_many

Save items(MovieClips) and dynamically create them

I made an invetory in AS3 which allows me to put items on slots in a closet, or in slots in the inventory. It completely works, but there is one problem.
In the game you are supposed to be able to buy new items and add them to the closet. I want this to be saved so that it is available the next time you play.
To do this, I want to save an Array to a SharedObject, then create the items dynamically from the array.
Right now I'm using the old fashioned hard coding for each object;
Itemwrench = new WrenchItem();
Itemwrench.x = par.toolCloset.kast_1.slotTC1.x + 400;
Itemwrench.y = par.toolCloset.kast_1.slotTC1.y + 245;
Itemwrench.gotoAndStop(2);
Itemwrench.name = "slotTC1";
Itemwrench.TC = 1;
NotinventoryParentTC.addChild(Itemwrench);
However, to add them dynamically I'd have to use getChildByName before it is added to the stage, which is not possible.
If possible could you show me how to do this correctly?
The information you need:
-The items are all stored in a closet with slots(Instances in the closet movieclip).
-The items need to get the name slotTC + the integer in a for loop.
-The name of the items change according to the slot number they are assigned when you take them out of the closet or put them back into the closet.
for(var i:int = 0; i < itemsInTC.length - itemsInTC.indexOf(e.currentTarget.name) - 1; i++)
{
nextSlotTC = "slotTC" + (itemsInTC.indexOf(e.currentTarget.name) +2 +i);
trace("Next Slot: " + nextSlotTC);
TempStrTC = "slotTC" + (itemsInTC.indexOf(e.currentTarget.name) +1 +i).toString();
trace("temp string: " + TempStrTC);
NotinventoryParentTC.getChildByName(nextSlotTC).x =
par.toolCloset.kast_1.getChildByName(TempStrTC).x + 400;
NotinventoryParentTC.getChildByName(nextSlotTC).y =
par.toolCloset.kast_1.getChildByName(TempStrTC).y + 245;
if(Boolean(NotinventoryParentTC.getChildByName(nextSlotTC)))
{
NotinventoryParentTC.getChildByName(nextSlotTC).name = TempStrTC;
}
}
This way I assign a new name and place them in the slot with the new name they received.
So now my question:
How do make it so that you can save the items to a shared object so that they are in the closet the next time you play the game.
Sorry for the long question.
Thanks in advance,
Milan.
You cannot directly store a DisplayObject in a SharedObject, as it contains memory links which will not be valid if you load such an object. A comon way to work around this is to store a significant data portion of that object. For example, you devise a following structure:
class SlotStructure {
public var slotID:int;
public var itemID:int;
public var itemName:String;
public var itemParameters:Array; // stuff simple types here
}
Then, for each of your items in inventory, you generate a SlotStructure object describing a particular inventory object. For your wrench it could look like this:
var ss:SlotStructure=new SlotStructure();
ss.slotID=1;
ss.itemID=getID(item); // assuming a function that returns a type of an item
ss.itemName=item.name;
ss.itemParameters=new Array();
for (var param:String in item) ss.itemParameters.push({name:param,value:item[param]});
Then you store an array of these into your SharedObject. To retrieve an inventory from a SharedObject you do:
public static const
registerClassAlias("SlotStructure",SlotStructure); // to be able to typecast from SO
for (var i:int=0;i<slots.length;i++) {
var ss:SlotStructure=slots[i];
var item:Item=new getClassFromID(ss.itemID)(); // a function that returns class
// say 1 - wrench, 2 - short sword, 3 - long sword, etc, one type=one ID
for each (var o:Object in ss.itemParameters)
item[o.name]=o.value;
placeIntoSlot(item,ss.slotID); // this does manipulation with x&y and display
}
A function getClassByID() might look like this:
private static const CLASSES:Array=
[StoneItem,WrenchItem,ShortswordItem,LongswordItem,...];
// manually stuff all your items in this!
public function getClassByID(id:int):Class {
return CLASSES[id];
}
The entire solution can be tailored to particular task, for example, in my game I have gems, that differ by location, type, size and score, so I store just these values and then I create new gems, set location, type, size and score with one function that sets all the other relevant parameters of that gem to align with stored info, and call it after making a gem with new Gem(). Your items might too be only worthy of a class name and ID in the class table, so store these with slot numbers and create objects that will have all their properties already set.

as3 dynamic variable within a loop

I need to have the screenPage var accessible for later calls. I am dynamically creating several pages. The issue is when I call screenPage.startDrag(); then it only drags the last page. How can I add a var in the name or make all the screenPages accessible through code?
Here is code in short:
var screenPage:MovieClip;
for(var p = 1; daTotalPages >= p; p++)
{
screenPage = new theFlagScreen();
}
Can I make screenPage a dynamic var and add like a 1 at the end and then a 2 and so forth with the loop?
Why not use an array ?
var pages:Array = new Array;
for(var p = 1; daTotalPages >= p; p++)
{
var screenPage:MovieClip = new theFlagScreen();
pages.push(screenPage)
}
Now you have an array containing all of your instances.
var myPage:MovieClip = pages[5] as MovieClip;
myPage.startDrag();
Also, the code you have above is creating an instance each time through, but since you then go ahead and create a new one each iteration and assign it to the same variable without storing it or adding it to the display list.... once you create a new one, the last one is marked for garbage collection.
The result is only the LAST instance you created still exists as it's the only one that has a variable that references it.
screenPage is a reference to just ONE thing. In your loop you keep overwriting it as you go and so you end up with it pointing to the very last instance of theFlagScreen... all the others are now lost.
You should follow prototypical's advice and store these instances in an array, that way you don't lose them.

AS3 class instances names

I really wonder. I made a MovieClip class Apple, I wrote a function that creates a new instance with a name "apple". Each time a new instance is pushed into an Array "apples". I call the function 5 times and I get 5 apples. I can manipulate them by calling them i.e. apples[0]. And when I trace my array I see 5 [object Apple] things. So maybe I don't really understand the structure of AS3 objects but shouldn't each object have a name?
When I set apple.name and get an array with 5 different names, I can't manipulate objects by names like apple1.x = 10. How does computer know which apple is where if each has own coordinates? Is the only way to call them: apples[0]-apples[4]? And if I create a code that should be same for all apples, how should I address the function, to "this"? Cause when I write class code I don't have any names yet...
For example, if I want to make Apple class a picture(MovieClip) that can be dragged, create any number of apples, up to a million, I can't possibly add apples[0].addEventListener, apples[1].addEventListener ... apples[1000000].addEventListener to the code. How do I make it global?
I'm asking cause when I'm directly coding for a specific instance, it has a name and I know exactly what am I addressing. And working with a class and making many objects I kinda don't... Sorry, I'm green
You don't need names to be able to access and manipulate your instances.
You can do something like this:
var apples:Array = new Array();
for (var i:int = 0; i < 100; i++)
{
var apple:Apple = new Apple();
apples.push(apple);
apple.x = Math.random() * 500;
apple.y = Math.random() * 500;
addChild(apple);
apple.addEventListener(MouseEvent.CLICK, onAppleClick);
}
function onAppleClick(e:MouseEvent):void
{
var ind:int = apples.indexOf(e.currentTarget);
var apple:Apple = apples[ind];
trace(ind);
apples[ind].visible = false;
//or
//apple.visible = false;
}
The same problem, huh? :)
For example Apple extends Sprite and inherits property name.
It's public, this means that you can change its name.
var apple:Apple = new Apple() ;
apple.name = "MegaApple" ;
Also, if you add the apple to stage, you can get him via name.
stage.addChild(apple) ;
get apple back:
var oldApple:Apple = stage.getChildByName("MegaApple") ;
But that never means, that you can use apple like that:
MegaApple.move() - because name of apple is supposed to be a property of apple, not a name of a variable.
Of course, you can create a lot of apples manually:
var apple1 = new Apple() ;
var apple2 = new Apple() ;
var apple3 = new Apple() ;
But if they all behave the same way, there is no point in doing. That's why you store them into array.
Hope you understand what I mean.