Home

ABCs of OOP Objects

ActionScript Example

A. Create An Object:

  1. Open Flash and create a new document.
  2. Using the Rectangle tool, draw a square with a color but no stroke.
  3. Convert it to a symbol (F8).

B. Give Object A Name:

  1. Click on the square to select it if necessary.
  2. In the Properties panel, give it an instance name of myBox.
  3. Move it the far left top edge of the stage.

C. Talk To Object and Tell Object To Do Something:

  1. Open the ActionScript panel (F9) and write the following code:
myBox.addEventListener(Event.ENTER_FRAME, moveBox)

  function moveBox(eventObject:Event):void
  {
    myBox.x = myBox.x + 1;
  }

NOTE: myBox.x = myBox.x + 1; basically says, "Get the current "x" property of the object and add one to it.

  1. Press CTRL+ENTER to test movie.

    TEST RESULT: You should see the box move SLOWLY across the screen one pixel at a time. (One-by-one, not much fun.)

  2. Replace myBox.x = myBox.x+1; with:

    myBox.x++; or with myBox.x += 1;

  3. Press CTRL+ENTER to test movie again.

    TEST RESULT: You should see same result. The myBox.x++; or myBox.x += 1; are shorthands for incrementing a value by one in most programming languages.

  4. Replace myBox.x++ or myBox.x += 1; with:

    myBox.x  += 10;

  5. Press CTRL+ENTER to test movie again.

    TEST RESULT: This time you should see the ball move FASTER (10 pixels every time the code is executed).

  6. Now, update the code with the changes in BOLD (Lines with double slashes (/*comment*/ and //) are comments and can optional be written.):
myBox.addEventListener(Event.ENTER_FRAME, moveBox)

function moveBox(eventObject:Event):void
{
/*Check to see if box "x" position is larger than stage*/
  if (myBox.x > stage.stageWidth)
  {
   //if so,set box "x" position back to zero.
   myBox.x = 0;
  }
  else
  {
   //Else, continue to move box by 10px repeatedly
   myBox.x += 10;
  }
}

NOTE: The main code has been "wrapped" with an "if/else" conditional statement which in essence says, "Check to see IF the box "x" position value is greater that the value of the stage's width and if so set the box "x" position back to zero ELSE continue animating as usual each time the code is executed.

  1. Press CTRL+ENTER to test movie again.

    NOTE: This time the ball REAPPEARS on the left of the screen after it reaches the right side of the screen.

  2. (OPTIONAL—FOR GEEKS ONLY).  Remove all of the carriage returns so the all of the code is on ONE line.  Be careful not to delete anything.  To reset it back to a more human readable code, click on the format code structure icon at the top of the ActionScript panel.
< Previous Topic     Next Topic >

© 2015. RMCS. All rights reserved.