Motion Tween versus Scripted motion

When motion is created on the timeline with frame by-frame animation, a motion or shape tween, it will play the same pattern every time the movie plays.

Watch the movie to the right. The red ball is controlled by motion tweens and moves the same way all the time. The yellow ball is controlled with the ActionScript below. It's motion is calculated and has a 25% chance of changing direction when it hits the left or bottom edges.

Motion can be created with ActionScript to control an object. The code can be typed into Notepad and saved with a .as extension into the folder containing the Flash movie. The most efficient way to do this is to define a class for this type of object in a .as file like this:

class Ball extends MovieClip {

  var moveRight: Boolean;
  var moveDown: Boolean;
  var randomChance: Number;

  function Ball()  {     
     moveRight = true;
     moveDown = true;
     randomChance = 0.25;

  function onEnterFrame(){     
    if(moveRight == true) 
        this._x +=8;
    else this._x -=8;

    if(moveDown == true) 
        this._y +=8;
    else this._y-=8;

    if(this._x <-10){
        if(randomChance > Math.random())
    if(this._x > 285)moveRight = false;

if(this._y <-10)moveDown=true; if(this._y > 285){ moveDown=false; if(randomChance > Math.random()) moveRight=!moveRight;} } }

A Ball is a movie clip object - this line is required.

It has 3 properties:

  • Is it moving right?
  • Is it moving down?
  • What is it's chance of changing direction?

When a Ball first appears it has the settings in red. It will move right, down and has a 25% chance of changing direction at the left or right edge.

As it enters each frame in the timeline it moves 8 pixels up or down, left or right.

this._x is the x position of this Ball. As x increases the position moves farther to the right.

this._y is the y position of this Ball. As y increases the position moves farther down.


When the Ball hits the left edge beyond an x value of -10, the motion has a 25% chance of switching the direction of motion from up to down or down to up.


When the Ball hits the right edge it will no longer move right (so it will go left)

When the Ball hits the top edge it will no longer move up. (so it will go down)

When the Ball hits the bottom edge it will have a 25% change of reversing direction from left to right or right to left.

To make this code work with your Flash movie clip, create the movie clip and right-click it in the library to choose linkage. Type in the name of the .as class file that defines how the object will behave. Check the boxes for Export for ActionScript and Export in first frame.

Now, the code in will control the motion of any mcBall you place on the stage.

Notice all the constants that are used in the code above: