Flash: Action Script 1

Start a new project and call the first layer 'text'. Click on the single Keyframe in the Timeline and press F9 (or Window/Actions) to open the Actions panel. Enter the code:

trace("My first program");

Choose Control/Test Movie to run the program. It should display the text in the Output box. Click the triangle in the top left corner of the Actions panel to send it back to the bottom of the screen.

Add three more keyframes at frames 5, 10 and 15. Click on each in turn and add some text to the screen such as 'Part 1', 'Part 2', etc. Play the movie and you should see the text appear and disappear in sequence.

Delete the code from frame 1 inserted above. Click on the second keyframe and in the Actions panel enter:

gotoAndPlay("part4");

This should play the movie without parts 2 and 3 because the instruction at part2 is executed immediately before the text there is displayed. The program loops continuously.

You could place similar code in each keyframe to make the parts appear in a different sequence.

Buttons

In this example we will make the four parts appear in response to clicking buttons on screen. Add a new layer, call it 'buttons', select it and then add a button to the stage. Drag three copies on to the stage (draw a circle, select it, convert it to a button symbol with F8 and then drag copies from the library).

Click on the first keyframe of the text layer, open the Actions panel and edit the code to read just:

stop();

(You could equally well add this to frame 1 on the buttons layer.)

Click on the first button and add this code:

on (press) {
 gotoAndStop("part1");
}

Add similar code to the other buttons so that each one jumps to the appropriate frame in the Timeline.

Movement

Insert an image onto the stage and position it on the left or right of the screen (find an image from Office clip art). Select the image, press F8 and convert it to a movie clip. If the image is on the left and you want to move it to the right then select the image and enter this code:

onClipEvent(enterFrame) {
 this._x++;
}

The onClipEvent handler executes the code each time the enterFrame event occurs; the enterFrame event occurs at whatever the frame rate is set to, the default being 12 fps. The keyword this refers to the object to which the code is attached, the image. The parameter _x refers to the x coordinate of the object on the screen and ++ increments (adds 1 to) its value. The x coordinate is a property of this (the image) so it is separated from the object by a dot.

Alternative code might be:

onClipEvent(enterFrame) {
 this._y+=5;
}

This adds 5 to the y coordinate, which will move the image object downwards on the stage 5 times more quickly than the first piece of code.

Conditional Statements

The last piece of code keeps moving the image off the stage and on forever. To send the image back to the top of the y axis we might use a conditional statement like this:

onClipEvent(enterFrame) {
   if (this._x > 400){
   this._x-=5;}  else {
        this._x=0;
   }
}

We could read the value of any variable in a program and take action depending on what it is. The value of a variable might change due to events in a movie and we could take any number of actions as a result.

Loops

We often want to do something more than once and the usual way to achieve this in programming is with a loop. For example, we might have a number of images on the screen that we want to move together. In ActionScript a for loop looks like this:

for (i=1; i<10; i++) {
  _root[tiger+i].x++;
}

Controlling Playback of Movie Clips

The commands for controlling a movie are:

These are  methods of a movie clip and are preceded by the movie clip's name, for example: myMovieClip.play.

In a new file add some buttons to control a movie clip. The movie clip should have a number of frames so create a new movie clip and add some elements to new frames. Use the commands above linked to button presses to control the movie.

Controlling Movie Clip Properties

The properties of a movie clip include the following:

These can be used to change the position, size and angle of rotation of a movie clip. For example:

on (press) {
fox._xscale+=1;
fox._yscale+=1;
}

This increases the size of a movie clip called 'fox'.

Dragging and Dropping Movie Clips

The location of the cursor is stored in two properties, _xmouse and _ymouse. Different objects can have x and y properties, for example movie clips or the movie itself. To get the properties of the stage we must use the _root object rather than this. To set the position of a movie clip to that of the cursor we need to set the _x and _y properties of the movie clip to the _xmouse and _ymouse properties of the stage:

onClipEvent(enterframe) {
 this._x = _root._xmouse;
 this._y = _root._ymouse;
}

In a new movie attach stop() to the single keyframe. Add an object that you can drag around and attach the above code to it. Be sure to add the name of the movie clip to the Properties panel - under the type of object.

You should then be able to drag the object around with the mouse. Note that the movie clip follows the mouse without a button press.

An alternative approach is to place a button inside a movie and add code to drag the button - this will ensure that the movie clip follows the mouse only when the mouse button is pressed over the it. To do this add an object, convert it to a movie clip (F8/choose Movie), give it a name and enter this name in the properties panel. Next add a shape to go inside the movie such as a rectangle; convert the shape to a button and double click it to edit it. Cut the shape from the Up part of the timeframe and paste it into the Hit part - this will make it invisible. Now add the code to the button:

on(press) {
 startDrag("",false);
}

on(release) {
 stopDrag();
}

Finally drag the movie clip over the button on the stage so they overlap. Run the movie and test dragging the movie around with the invisible button.

Levels

Movie clips can contain other movie clips, like Russian dolls. To access one movie clip inside another the dot notation is extended, for example: MovieClip1.MovieClip2.variable ++. This means that each movie clip can contain variables with the same name. Each level can have its own variables with the same names.

One way to demonstrate levels is to place movie clips inside each other. Add a rectangle to the stage taking about one third of the area available. Select the rectangle and convert it to a movie clip called 'level1'. Remember to add the name of the movie clip to the box in Properties. Add a piece of dynamic text to the movie clip, enter 0 to initialise the display and make sure the font colour is different to the background. Set the 'Var:' property to 'testVariable'. Add a button to this level and set its code to:

on (press){
testVariable++
}

Now add another rectangle inside the level1 movie clip and convert it to a move clip called level2 - remember to add its name to Properties. Double click level2 to edit it and add a piece of dynamic text and a button exactly as before. Add the same code as above.

Click the blue arrow in the Scene toolbar twice to return to the stage. Draw a rectangle and place the two nested movies inside it. Add a piece of dynamic text, a button and the same piece of code.

Test the movie (Ctrl-Enter). Clicking the different buttons should increment the text box values separately, showing there are three variables with the same name at different levels of the movie.

Add three new buttons on the stage and attach this code to them:

on (press){
testVariable++;
}

on (press){
level1.testVariable++;
}

on (press){
level1.level2.testVariable++;
}

Duplicating Movie Clips

A Flash movie may often need to create copies of itself when the movie is running - especially in games where new objects are created as old ones are destroyed. Flash has the command DuplicateMovieClip that is triggered by the movie clip that is to be duplicated. The DuplicateMovieClip command takes two parameters, the name of the new clip and the level of the new clip. The word level is used here to mean the order in which the duplicates were created rather than the level of nesting used in the previous section.

 Sample code:

on (press) {
originalclip.duplicateMovieClip("newclip"+level,level);
_root["newclip"+level]._x = int(Math.random()*550);
_root["newclip"+level]._y = int(Math.random()*400);
level++;
}

The name 'originalclip' (or whatever) would have to be set in the Name property of the movie clip properties panel. This code would be attached to a button and would duplicate any appropriate movie clip. The first keyframe in the overall movie clip would contain:

level = 0;
stop();

This initialises the level variable used in the on (press) handler. The object to be duplicated should be named in the Properties section of the clip. The code duplicates this clip, assigns it a name with a number at the end that increments each time through and assigns a random location on the stage from the x and y properties of _root.

Movie clips can be removed with the removeMovieClip command. This code also uses the attachMovieClip command to create a new movie clip:

on (press) {
_root["newclip"+(level-1)].removeMovieClip();
attachMovie("anyMovieClip","newclip"+level,level);
_root["newclip"+level]._x = int(Math.random()*550);
_root["newclip"+level]._y = int(Math.random()*400);
level++;
}

The attachMovieClip command does the same as duplicateMovieClip but it can work on a movie clip that is in the library and not on the stage. attachMovieClip has three parameters for the name of the source movie, the name of the new movie and the level of the movie.

Multiple Movie Clips

Rather than have the same code attached to identical multiple movie clips it is better to put the code in one place. We can create a movie clip off-stage and use it to control all the clips of one type that appear on-stage. Add a small text box with the word 'actions' in it and convert it into a movie clip.

Now create a symbol to control and set its linkage properties in the Properties box to Export for ActionScript with a suitable name. The code will handle the event of the movie clip being loaded.

onClipEvent (load) {
for (i=0;i<10;i++  {
       _root.attachMovie("name","name"+i,i);   //new movie clip
       _root["name"+i]._x = i*50+50;   //increase x location by 50
       _root["name"+i]._y = 200;        //keep y location constant
     }
}

onClipEvent (enterFrame) {
for (i=0;i<10;i++  {
   _root["name"+1]._rotation += 5;
}

Exercise: design a gear symbol with 12 teeth. Set the gear symbols to load next to each other so the teeth interlock. Rotate alternate symbols in opposite directions, just as they would if one of them was driving the others.

Detecting Collisions

The main way to decide if two objects on the stage have collided is to use the hitTest function, which can evaluate either the location of a point or a movie clip.

You may want a script to detect whether the user's mouse is over an object on the stage:

onClipEvent (enterFrame) {

  if this.hitTest(_root._xmouse, _root.ymouse, true)) {
    this._x = int(Math(.random()*550);
    this._y = int(Math(.random()*400);

This makes an object move away from the mouse to a random location. You could use the function to detect a collision:

onClipEvent (enterFrame) {
  if (_root["target"].hitTest(_root["bullet"])) {
     _root["target"]._xscale += 5;
     _root["target"]._yscale += 5;
     _root["bomb"]._x = 350;
   } else {
     _root["bomb"]._y += 5;   //move bomb
  }
}

This assumes two movie clips called target and bomb. The bomb moves down the screen, if it meets the target the target gets bigger.

Jumping to Frames in Movie Clips

Some movie clips have just one frame but if they have many frames then it is possible to jump to any one of them through ActionScript. This is much quicker for a change of image than removing one clip and loading another. A movie clip could be created that has a number of frames that together produce an animation (such as the eyes seen earlier). Then any frame of the movie could be accessed by naming each frame (frame label) and jumping to that frame by, for example, a button press:

on (press) {
movieclip.gotoAndStop("label");
}

The gotoAndStop function jumps to the named frame and stops there.

Keyboard Input

To get input from the keyboard use code like this:

on (keyPress "<Right>") {
shape._x++;
}

This code is attached to a button that is parked off the stage so it is not visible. Nevertheless its code still runs and it processes the key presses and takes action accordingly. The left, up and down arrow keys can be processed in the same way.

This code does not use a button but is attached to a movie clip. The movie clip is created as a piece of text containing a word such as 'actions' that is parked off the stage. This is made into a movie clip, which contains the code to control the behaviour of any other movie clips. A movie clip called 'shape' is added to the stage and the following code can then be used to control it:

onClipEvent(enterFrame) {
if (Key.isDown(Key.RIGHT)) {
_root.shape._x++;
}

if (Key.isDown(Key.LEFT)) {
_root.shape._x--;
}

if (Key.isDown(Key.UP)) {
_root.shape._y--;
}

if (Key.isDown(Key.DOWN)) {
_root.shape._y++;
}
}

You should now be able to write code that moves shapes around the screen and detects if a collision has occurred with another object.

onClipEvent(enterFrame) {
if (Key.isDown(Key.RIGHT)) {
_root.circle._x++;
}

if (Key.isDown(Key.LEFT)) {
_root.circle._x--;
}

if (Key.isDown(Key.UP)) {
_root.circle._y--;
}

if (Key.isDown(Key.DOWN)) {
_root.circle._y++;
}
if (_root["shape"].hitTest(_root["circle"])) {
_root["shape"]._xscale += 5;
_root["shape"]._yscale += 5;
}
}

Sounds

We can add sound to the previous code as follows:

mySound = new Sound();
mySound.attachSound("newalert");
mySound.setVolume(50);
mySound.start;

 

Home