Thursday, October 30, 2008

AS3 04 - More About Instances

From the previous post… what we have done is adding a rectangle manually in the stage and repositioning it via AS3. What if we want to add additional rectangle? Are we going to draw it out one by one? In a game, we are most likely to add enemies… waves and waves of enemies. We draw / import a sample enemy (in this case… a movieclip we created earlier called ‘myRect’) into the library and make copies (instances) of them on the fly on the stage whenever we need them. Get it? I just referred to the movieclip = sample enemy and instances = copies of enemies.
Now in order to make copies of the enemies we need to refer to the original sample enemy (in the library called ‘myRect’ – remember we tick on the ‘Export for ActionScript’ when we created the ‘myRect’ symbol? Take note on the class name on the Linkage section because that’s the class we are refering to. What do you mean no?). Here we create the new instance from ‘myRect’ with the name of ‘myRectIn2’

var myRectIn2:myRect = new myRect();

Now that we have the name of the second rectangle, we can reposition it like what we did with the first one.

myRectIn2.x = 200;
myRectIn2.y = 200;

Now the second rectangle is not gonna be displayed on the stage unless we add it into the stage thus….
addChild(myRectIn2);

or
stage.addChild(myRectIn2);

whichever you prefer… they both work… which brings to the point that what I wrote here isn’t necessarily the only method to achieve similar results.


This article has been brief because I am lazy not because I am lazy but I would like to streesss on the importance of not mixing or confused symbols reference in the library with instances references of the symbols because I always make this mistake when I started out and therefore they deserve an entire post for it.. (other than the one before this) err.. themselves...hmm. You will need to use these lots in future if you are interested to read more of my rumblings to pursue a higher karma understanding of stuffs yet to come. What the??

No comments: