CS 325 and Film 385: Introduction to Flash Scripting part 2


flash icon

Highlights of this lab:

  • Extending Symbols
  • Interpreting Keys
  • Application: Particle Systems
  • Application: Games
  • Adding Your Flash Movie to an existing Webpage
  • Assignment

:: Extending Symbols ::

You can extend the behaviour of symbols to make them "intelligent". They can have a script of actions to follow in response to key and mouse clicks, as well as a a script to control what they do in general. There are many reasons to want to do this. You will see some reasons why in our application examples.

The ActionScript 3 is object oriented. This means you can add functionality, such as movement programs, onto existing items, such as Buttons and MovieClips. To do this you create an ActionScript file. This is a separate program that you will add into your project. The program is then attached to a symbol of the appropriate type and it's program will then affect the behaviour of the symbol.

The basic steps are:


:: Interpreting Keys ::

Interpreting keys is similar to receiving Mouse events. You create add an event listener for KeyboardEvent type events. Most of the time you want to add the listener to the stage, but it is possible to add it to other things, like text fields.

For each key there are two major events - a KEY_DOWN and a KEY_UP event. If you want to do something just once when a key is pressed, you usually only listen for the KEY_UP and do it when the key is released. If you want to repeat an action you use the KEY_DOWN and set a flag that says the key is pressed and perform an action in your update (ENTER_FRAME) event behaviour. You unset the flag when you hear a KEY_UP that says the key was released.

Each key has a special code associated with it.

See the Capturing Keyboard Input and Keyboard Object Reference sections for more details.


:: Application: Particle Systems ::

A particle system is a combination of a generator and objects. The generator introduces little independent animations called particles into a scene. You see them all the time in movies and video games. The generator controls things like: where the animation started, how fast the particle was moving when it started, how buoyant the particle is, and how long the particle lives. Many particle systems are custom made for a particular situation, but it is possible to make one sufficiently abstract to represent such diverse things as fog, explosions, smoke, and sparkles simply by adjusting the generator and the pictures in its animation.

Here is the system you will make in the lab:

The little red ball represents the generator. Currently it moves when you press the arrow keys. Its initial position can be controlled by moving it around on the stage. We will start by making a moveable generator, then we will create intelligent particles and finally we will make the particles appear where the generator is.

Making the Generator and Adding Basic Keyboard Controls:

More Advanced Keyboard Controls:

 

Create an ActionScript File to Control Particle Behaviour

Here we will create a file that has nothing but pure ActionScript in it. This can be attached to a symbol later to give it behaviour. This technique allows us to easily share behaviours between symbols in the same project and in different projects.

Create a Bubble Movie Clip and Give it Particle Behaviour

Starting up the Particle Generator:

Instead of placing particles manually we will use the particle generator to add particles to the animation. We will use a random number generator so start them moving in different directions and at different speeds.

 


:: Application: Games ::

Here is a sample of the game you will make (plus a few undocumented extras):

 

This one is structurally simpler, but more interesting to play. It still requires only two files.

Prepare the Stage:

Main Timeline Code:

//The comments explain how the code works
//Create comments by adding "//" before text on a line

//the function below stops the application from going to the next frame.
// the ; at the end of the line marks the end of the statement.
stop();

//Create variables for the score and high score and set them to 0.
var score:Number = 0;
var highScore:Number = 0;
var lvl:Number = 0;

//A list to hold the alien ships.
//This list would allow us to:
// remove all ships from the screen
// check to see if a ship was hit by a bullet instead of a mouse click
var ShipList:Array = new Array();

//Add a listener for when Flash starts this frame
addEventListener(Event.ENTER_FRAME, mainEnterFrame);

//This is the function called when we enter this frame
function mainEnterFrame(event:Event):void
{
// "{}" or curly brackets mark the beginning and end of a block of code
// usually for a function or if statement
var alienSpawn:Number = Math.random();

//if the number is above the cutoff then add an alien to the game
if (alienSpawn < lvl / 200.0 + .01)
{
//the makeObject function will add an object to the stage at a position
makeObject("Scripts.Alien", -40, Math.random()*440);
}
}

//makeObject is not built-in to Flash... we need to write it ourselves.
function makeObject(className:String, startX:Number, startY:Number):void
{
//find the class "className" in Flash so you can create a new instance
var myClass:Class = getDefinitionByName(className) as Class;

//declare new object using the dynamically obtained class name
//Here, "this" refers to the current frame - also known as the referrer.
//The current frame will be responsible for the new object we create.
var instance:DisplayObject = new myClass(startX,startY,this);

//Add the ship to a list of ships
ShipList.push(instance);

//add the object as a child to the stage (display object container)
this.addChild(instance);
}

function gameOver()
{
//game over
//update highscore if this is a new highscore
if (score > highScore)
{
highScore = score;
}

//Clear the screen of Alien Ships
var instance;
while (ShipList.length > 0)
{
instance = ShipList.pop();
instance.remove();
}

//reset the score and level to 0
score = 0;
lvl = 0;

//Update the score text
scoreText.text = "Score: " + score +
" Highscore: " + highScore +
" Level: " + lvl;

}
 

Create an Actionscript file to control alien ships

Alien Ship (Button) code:

//package helps define the folder where this external code is located
package Scripts
{

    import flash.display.SimpleButton; //The ship will be based on a button.
    import flash.events.Event; //This allows us to listen for frame refresh.
    import flash.events.MouseEvent;    //This allows us to handle mouse clicks.
    import Math;

    //Add Alien ship behaviours to a button by "extending" button behaviour.
    public class Alien extends SimpleButton
    {
        var referrer; //you need this later to adjust the score.
        var speed:Number; //controls ship speed
    
        //Constructor function for Alien class
        //This is executed whenever you make a "new" Alien.
        //    startX: initial horizontal position
        //    startY: initial vertical position
        //    refer:    reference to the stage
        public function Alien(startX:Number, startY:Number, refer)
        {
            //Randomly set the size and speed of each ship.
            //Math.random() generates numbers between 0 and 1 inclusive.
            var scale = 0.2 + Math.random() * 0.8;
            scaleX = 0.3 + scale;
            scaleY = 0.3 + scale;

            //Set the speed so it reflects the size of the ship. 
            speed = 5.0 * scale;


            //save the initial position of the ship
            x = startX;
            y = startY;

            //save the reference to the stage
            referrer = refer;
            
            //Add listener for frame refresh so we can update the ship's position
            this.addEventListener(Event.ENTER_FRAME, shipUpdate);
            this.addEventListener(MouseEvent.CLICK, shipHit);
            
        }
        
        //This is the ship click handler
        //When a ship is clicked you should update the score and remove the ship
        public function shipHit(event:MouseEvent):void
        {
            //Add points to the score.
            referrer.score = referrer.score + 1;

            //Move to a new level every 10 hits.
            referrer.lvl = Math.floor(referrer.score/10.0);
            
            //Update the score text
            referrer.scoreText.text = "Score: " + referrer.score + 
                                  " Highscore: " + referrer.highScore +
				  " Level: " + referrer.lvl;
                                      
    
            //remove from list of Bad Guy Ships (used to clear screen when game ends)
            referrer.ShipList.splice(referrer.ShipList.indexOf(this),1);

            //free the object and its dynamically allocated components
            remove();
        }
        
        //This is where most of the game logic is.
        //  Update position
        //  if an alien crosses the screen completely game is over
        //  when game is over set highscore, clear score, and clear board.
        function shipUpdate(event:Event):void
        {
            //move the alien to the right
            x = x+speed;
            
            //Uncomment this to increase difficulty
            //y = y+Math.cos(x/20)*speed;
            
            //test to see if the alien has moved across the screen completely
            if(x > 640)
            {
                //This function clears the board.
                referrer.gameOver();
            }
        }
        
        //function that removes an object properly
        public function remove()
        {
            //remove listeners
            this.removeEventListener(Event.ENTER_FRAME, shipUpdate);
            this.removeEventListener(MouseEvent.CLICK, shipHit);

            //remove from parent item's display list
            this.parent.removeChild(this);

            //delete object from memory
            delete this;
        }
    }
}
 

Create an Alien Ship Symbol and Hook it up to the Code

There are many places to add behaviour. For example:


:: Assignment ::

For this lab assignment I want you to follow the instructions for this lab and create a particle system and a game. You can combine the two - use the particle system with appropriate settings to create an explosion.

Submit published .html and .swf files, and all your resources in a folder or zip file with the lab number and your name on it. This is due at the beginning of your next lab. Have fun!


..:: Web [Re]Sources ::..