Wednesday, October 29, 2008

AS3 03 - On stage instance

My previous post deals with tracing items in the output window and getting the input from keyboard presses. Now those are great for filling in blog spaces basics that well err... need for er... basic understandings. Now that you know that the event listeners are the way to go, you can now start to add stuffs to the stage and making them move about.

Here is what we are going to do in this tutorial.
  • First we go about adding an item to the stage
  • Next, we script in AS3 to perform certain things to the item on stage

Simple stuffs? Yeah right. Let's start shall we?

Start with a new Flash File (ActionScript 3.0). Draw something on the stage. Anything at all... well not really anything... A simple circle or square would be nice. Well, mine is a rectangle and it looks like this...

Now 'right click' on the perfect looking triangle... I mean rectangle and choose the 'Convert to Symbol' option.

Next, name the symbol as 'myRect' follow this name or die!!! for convinience sake. (Sake? or sake as in sa ke for Japanese rice wine?). Make sure to 'check/tick' the checkbox for 'Export for ActionScript' so that we can refer to the item in AS3 instead of mindlessly wondering around what went wrong later on.

Now try this...

Open up the ActionScript Editor for Frame1 and type in...

myRect.x = 100;

The rectangle should move to 100px from the left of the stage. Well does it happen? What you get from that is an error. This is one of the common error poeple faces when starting out scripting (well at least that was what happned to me...) What happened was the script was trying to refer to an instance in the stage while you actually is trying to point to the movieclip in the library. You need to name the instance of the movieclip you created which resides on the stage. Confuse now? If you look at the image below, you can notice when you click on the myRect instance on stage, the properties on the left shows . Type in 'myRectIn' to name the instance of the myRect which is on the stage.

Once done, you may type in

myRectIn.x = 100;

It works! Now the rectangle is paced 100 pixel from the left of the stage. I hope you grab this concept of MovieClip and Instance on and off stage. This is by far considered very dear and costly if you didn't really grab what I am trying to put forward here. I will end here so that you can think about your future instead of reading this...

No comments: