TGJ2O_Animating_Actionscripting

=include component="page" wikiName="jmcintyre" page="course_tabs_header" = include component="page" wikiName="jmcintyre" page="menu_tgj2o_animation"

=Creating a Flash Lite Game - Tutorial= By [|Blue_Chi] | Flash CS3

Making rich media for mobile consumption has never been easier since the release of the Flash Lite player for mobile devices. You can make a vector graphics game that could be played on any device regardless of its operating system or screen resolution easily as long as that device is equipped with the Flash Lite player - and lets not forget that you can play that game on a PC as well without using any emulators because the file is still a Flash movie that could be played on the Flash Player. This tutorial will teach you how to create a Flash Lite game playable on the Flash Lite Player version 1.1 - one of the earliest versions and most restricted, but the most widely spread version as well. Our basic game could be created without using the advanced features provided in later versions. Adopting Flash Lite 1.1 will guarantee that the game will be compatible with the largest possible number of Flash Lite powered devices. The game we will create is a very basic arcade game, the player merely collects the objects before they reach the ground. If he fails to collect three objects then the game ends. Our game will use very simple ActionScript concepts such as [|variables] and [|conditionals]. You really do not need to know much else.

Link to the [|original tutorial]

What's Behind the Code?
As previously stated, our game uses very basic ActionScript concepts, as each of the objects fall, the value of their location on the _y axis increases, we run a conditional that checks if the player coincides with any of the fallen objects at the same position, if it is that is the case, the player gains an extra score point. Another conditional checks if the object reached the ground, if it does, the player loses one life. It is that easy!

Game Structure
Our game will require **five** frames only, they are as follows: > The user will see a screen that says start game, he has to press a button to start playing. > All objects and variables required for the game will be created in this frame. This code needs to be executed once only and that is why it is separated from the rest of the code that will have to be repeatedly executed. > This frame will have the actual code to run the game, it will control the movement of the objects during gameplay and will continuously run throughout the game. > This frame has the simple task of making the previous frame loop. It does not have any other task or code. > The player is transferred to this screen when he consumes all his lives. This screen will show him his final score and will also give him the option to play again. This is the basic structure for creating a game on any platform. Making a game in Flash is easier to understand because you can separate the code of each of these sections in different physical frames. We will go through them one by one, but first we will create the basic layer structure to organise the content in each of our frames.
 * 1) **Game Start**
 * 1) **Initialization**
 * 1) **Game Execution Loop**
 * 1) **Game Loop 2**
 * 1) **Game Over**

Step 1- Layer Structure
Create a new Flash Lite movie, you can use Adobe Device Central, or alternatively create a regular Flash file and change the ActionScript version from the Publish settings. Set the ActionScript version to //Flash Lite 1.1//, the dimensions to //240x320px// and the framerate to //12fps//. You should have one layer in your movie. Add //three extra// layers to the timeline, and rename them to //Actions//, //Buttons//, //Main Content//, and //Background//. Each of these layers will host a specific type of content as labelled. We will now create keyframes in each of these layers in accordance with the **5 Frames** structure illustrated above. Start off with the //Actions// layer. Create //5// separate //keyframes// in it. Now for the //Buttons// layer, we need a keyframe in //Frame 1//, //Frame 2//, //Frame 3//, and //Frame 5//. The //Main Content// layer on the other hand needs a keyframe in each of //Frame 1//, //Frame 2//, and //Frame 5//. We are going to have only //one keyframe// in our //Background// layer, make that frame span across all the five frames. Our timeline is now ready. We will start working on each of the frames in turn: You are now set to start making the game, the **Game Start Frame** is naturally next.
 * **Frame 1:** Game Start
 * **Frame 2:** Initialization
 * **Frames 3 and 4:** Game Execution Loop and Game Loop 2
 * **Frame 5:** Game Over

We will create in this section the **Game Start Frame**. This frame will stop the game from playing instantly and will contain the title text and the button to make the game start when the player presses the 'Enter' button. In order to follow this tutorial, you will have to download [|game_assets] that contains the graphics for our game.

Step 2 - 'Game Start' Frame
We will start working from the bottom layer going up. Starting with the background, select the //Background// layer, then import (//File>Import>Import To Stage//) the //background.gif// image to it. If the image is not automatically aligned at the right place, you have to make sure it does by doing that manually. Once you do that, //lock// this layer. The same background will be displayed throughout the game so we don't have to make any changes to it. For the main content in this frame we are going to have text that says //Start Game//. Select the //Main Content// layer and then use the //Text Tool// to create such text, you can use any font, colour, and font size you wish for this. You can also add any graphics for a logo or anything of that sort in this frame. Make sure that you have your text type set to **Static** (Check the **Properties Inspector**), if you use any other text type you will have to embed the characters before hand to make the text visible at run-time. Even though no physical button will be required as the navigation is going to be through the phone keypad, Flash Lite 1 can only register key presses through a button symbol, so we will have to create one. Select the //Buttons// layer and use the //Oval Tool// to draw a little circle **above the stage** - our button should **not** be seen. Now use the //Selection Tool// to select this circle and then press //F8// to convert it to a //Button Symbol//. Name it //MyButton//. We will keep using an instance of this object each time we want to register keypad presses. We will start putting some Actions now. //Right-click// our button, select //Actions//, and then paste the following code in the Actions Panel. This code will be assigned directly onto the button.

on (keyPress ""){ play; }

The code is self-explanatory, if the button "Enter" is pressed, the movie will be played. Of course, the movie by default should be playing, but we do not want to it to do that, so we will make it stop. To do this, first close the Actions panel, //select// the //Actions// layer, then //right-click// the first frame and select //Actions//. Paste the following code:

stop;

NOTE: Something annoying about Flash CS3, if you want to **assign a script to a certain frame,** you will have to do the following: **(1)** select the layer of that contains the frame, **(2)** click on a faraway empty frame in the same layer - for example, frame 10 in our case, **(3)** now right-click the frame that you want to assign (frame 1 in our case) and select Actions. It doesn't make sense, but that's how it works. An essential command to set at the first frame along with the //stop// method is one that switches the player to fullscreen mode. Add the following code below the //stop// command to do that:

fscommand2("fullscreen", true);

We are done with our **Game Start Frame**, here is a summary of what we did: I hope that you found this section easy. We will now move to the **Initialization Frame**.
 * 1) Added the background to the //Background// layer.
 * 2) Added the title text to the //Main Content// layer.
 * 3) Added the button to the //Buttons// layer and assigned the //play// method to the button.
 * 4) Assigned to the //Actions// layer the code to //stop// the movie and started the //fullscreen// mode.

In this stage we will create the **Game Initialization Frame**, the code in this frame runs only once to create all the objects we need for the game, it also creates the starting values for variables in the game such as the game score and the number of lives the player has. We will start with the different types of content we have from the bottom up, the background is already done from the first frame, so we will move straight into the //Main Object// layer.

Step 3 - Creating the Player and the Target Objects
Our //Main Contents// layer will host the //Player// and the //Target// that will be caught during the game. Assuming that you have already unzipped the file given in the previous page. Import the included //player.swf// movie into your library (//File>Import>Import to Library//). Open the //Library// (//Ctrl+L//) and drag an instance of your player onto the //second frame// of our //Main Contents layer//. The location of the player object on stage does not matter because we will it later position using ActionScript. We have to convert this graphic to a Movie Clip Symbol to do that though. So select it, and then press //F8// to convert it to a Symbol. Assign the name as //MyPlayer//, set the type to //Movie Clip//, **and then change the //Registration Point// to the //top left corner// as indicated in the image below.** **Registration Point:** Setting the registration point to the left makes it easier to position the object in our game. When you set the _x position to Zero this means that the left side of the object would be at the point Zero and not the center of the object ilke what happens with default settings. This makes things so much easier, especially as player's width equals exactly the 1/3 of the stage's width, so the three positions that it has to be at are 0, 1/3, and 2/3 of the width of the stage. Before we forget, you have to also assign the //instance name// //player_mc// to this movie clip using the //Properties Inspector//. Our game is going to have three targets falling at the same time, we will create these three targets using ActionScript, but we need to have the source template for the target from which we will duplicate our additional copies. You will have to import the //target.swf// file included in the zip file you downloaded earlier, go through //File>Import>Import to Library// to do just that, then open the library (//Ctrl+L//) and drag a copy of it onto the //Main Contents// layer. You have to position this object somewhere above the stage because we do not need to see it during run time. //Convert// to a //symbol// (//F8//), set the //registration point// to the //top left// corner, //name// the symbol //MyTarget//. Click //OK// and then assign the //instance name// //target_mc// to it.

Adding the Score and number of Lives display
The player needs to see the number of points he scored and how many lives he has remaining. We will do that by creating the text labels and then a couple of dynamic text fields to show the actual numbers. Start off by using the //Text Tool// to write two texts that say //score// and //lives//, make sure that the text type of each of these texts is //static// (check the //Properties Inspector//). We will now create the dynamic texts that will actually display the numbers for each of these variables. **Make sure that no text is selected**, pick the //Text Tool,// access the //Properties Inspector// and set the text type to //Dynamic//. Now draw a text field next to score, set the font to //_sans//, font size to //11//, and align the text to the //left//. You will now have to assign the //variable name// //score// to it to display that variable when it is created. Create another field next to the text that says //lives//, use the same properties as above and assign the //variable name// //lives// to it. You should end up with a screen similar to the one below. We used the system font _sans to avoid embedding any characters as would usually be required when using a Dynamic text field. That completes all the visual content of this frame, we will skip the //Button// layer because there are no navigation commands in this frame. We will move to the Actions now.

ActionScript
//Select// the //Actions// layer, //right-click// the //second frame// and select //Actions//. (Might need to use the trick mentioned in the [|previous page] regarding Frame selection for ActionScript). Paste the code below to initialize the game assets. The code is pretty simple. The first two lines are the basic variables which we are using, the score (starts at zero) and the lives (player has three lives). we are setting the _x and _y properties of the player_mc object, and then duplicating the target_mc three times, the actual target_mc will not be used again. Each of the new targets will be set at their position horizontally, and will be placed at a random position above the screen before falling, I used a random value here to make sure that they don't all fall together making it hard for the player to catch all three objects at the same instance.

score=0; lives=3;
 * Essential Variables**

player_mc._x=0; player_mc._y=280;
 * Positions the player on the stage.**


 * Creates 3 targets by duplicating the one on stage** duplicateMovieClip("target_mc","target1_mc",1); duplicateMovieClip("target_mc","target2_mc",2); duplicateMovieClip("target_mc","target3_mc",3);

target1_mc._x=0; target1_mc._y=-random(40);
 * Positions the new targets above the stage ready to play**

target2_mc._x=80; target2_mc._y=-random(40);

target3_mc._x=160; target3_mc._y=-random(40);

We would like our targets to fall at different speeds, so we will assign a different speed property to each of these targets. The //speed// property will be used when the game actually runs, but we have to assign it now. The initial speed will be a random number between 0 and 10. If the speed is actually zero, the targets will not move, so we will be adding the number //4// to whatever speed we get. We could have used //1// instead of //4//, but playing at speed //1// is way too boring. The code was changed this way:

score=0; lives=3;
 * Essential Variables**

player_mc._x=0; player_mc._y=280;
 * Positions the player on the stage.**


 * Creates 3 targets by duplicating the one on stage** duplicateMovieClip("target_mc","target1_mc",1); duplicateMovieClip("target_mc","target2_mc",2); duplicateMovieClip("target_mc","target3_mc",3);

target1_mc._x=0; target1_mc._y=-random(40); //target1_mc.speed=random(10)+4;//
 * Positions the new targets above the stage ready to play**

target2_mc._x=80; target2_mc._y=-random(40); //target2_mc.speed=random(10)+4;//

target3_mc._x=160; target3_mc._y=-random(40); // target3_mc.speed=random(10)+4; //

We need to create a variable to store the location of the player on the stage and to check for it at the time the objects fall, we can recall the position at run time, but checking for a number like that can be messy, to have a nicer and a more understandable code we are going to create a property called //myPosition// to tell us if the player is at position //1// (the left), position //2// (the center), or position //3// (the right). At the start, the player is as the left (_x=0), so his position is 1. This will make much more sense by the end of the next frame. score=0; lives=3; player_mc._x=0; player_mc._y=280; //player_mc.myPosition=1;// duplicateMovieClip("target_mc","target1_mc",1); duplicateMovieClip("target_mc","target2_mc",2); duplicateMovieClip("target_mc","target3_mc",3); target1_mc._x=0; target1_mc._y=-random(40); target1_mc.speed=random(10)+4; target2_mc._x=80; target2_mc._y=-random(40); target2_mc.speed=random(10)+4; target3_mc._x=160; target3_mc._y=-random(40); target3_mc.speed=random(10)+4;
 * Essential Variables**
 * Positions the player on the stage.**
 * Creates 3 targets by duplicating the one on stage**
 * Positions the new targets above the stage ready to play**

Initialization is now done. In this stage, we did the following: Glad you have made it to this frame, the main **Game Execution loop Frame** is next.
 * 1) Added the //player// object to the //Main Contents// layer.
 * 2) Added the //target// object to the //Main Contents// layer.
 * 3) Added the //score// and //live// displays in the //Main Contents// layer.
 * 4) Assigned the //Actions// to create the essential //variables//.
 * 5) Assigned the //Actions// to position the //player//.
 * 6) Assigned the //Actions// to duplicate the //target//.
 * 7) Assigned the //Actions// to position and configure these new targets.

The **Game Execution loop Frame** holds the code that runs the game, controls the objects, counts the score and takes away lives when you fail to catch the object. Our frame will also configure the controls for moving the player on the screen, we will start with this last part first. We have already created and aligned all our visual objects in our previous frame so we can move straight into the stage to create the button that captures key presses and then code the game loop.

Step 4 - Creating the Game Controls
We need to create the button to hold the control code, //select// the //Buttons// layer, open up the //library// (//Ctrl+L//) and drag an instance of the //MyButton// symbol we created earlier, make sure that it placed somewhere above the stage so that it is not visible during the game. //Right-click// this instance of the button on the stage and select //Actions//. We are going to use **two buttons** only to control the player, we are going to use a very simple [|conditional] to move the player and change the value of its //myPosition// variable depending on where it currently is.

on (keyPress ""){ if (player_mc.myPosition != 1){ } }
 * player_mc.myPosition--;**
 * player_mc._x-=80;**

on (keyPress ""){ if (player_mc.myPosition != 3){ } }
 * player_mc.myPosition++;**
 * player_mc._x+=80;**

The code is simple, as long as the position of the player is not //1// (absolute left), then pressing the left key button moves it to the left by //80// pixels, and as long as the position of the player is not //3// (absolute right), then pressing the //right// key button moves it to the right by //80// pixels. The player movie clip is exactly //80// pixels in width, which is also exactly //1/3// of the width of the stage, so moving it by //80// pixels to the left or the right is a whole step to the left or the right. I find using the //myPosition// property easier because I do not have to think about the actual positions when making my conditionals, although those would work the same if you use the exact values. We will also be using this variable later on below to check if the targets are caught.

Coding the Game loop
We have to assign our biggest chunk of code to //Frame 3// of the //Actions// layer. Select that frame and open the //Actions// panel. We are going to do this in segments, I will explain each one as we go through. Most of our code will be duplicated three times, each for one of the targets. Our first task is to make our objects fall down, we do that by increasing the //_y// property of each target, we will add to them the value of the //speed// property we set in the previous frame. Each object has a different //speed// value, so they should be falling at different speeds.

Commands the targets to move downwards. target1_mc._y **+= target1_mc.speed;** target2_mc._y **+= target2_mc.speed;** target3_mc._y **+= target3_mc.speed;** The next task is to configure what happens when the balls reach the ground without being caught. We know that the height of the stage is //320// pixels, so if the //_y// property exceeds that the target has fallen down. If that is true, then the player loses a life, and then the ball is thrown up to a random place above the stage (that's the new //_y// is negative), and the //speed// is set as a random value between zero and the current score (plus 4 to avoid zero speed). This makes the game become faster as you score more. You paste the following below the first segment:

The targets fall down. if (**target1_mc._y>320**){ lives--; target1_mc._y =-random(40); target1_mc.speed= random(score)+4; } if (**target2_mc._y>320**){ lives--; target2_mc._y =-random(40); target2_mc.speed= random(score)+4; } if (**target3_mc._y>320**){ lives--; target3_mc._y =-random(40); target3_mc.speed= random(score)+4; }

Now what happens if our targets are actually caught? First, each target will be caught under a different condition, each will have to have its //_y// property lower than //250//, and then the //player// has to be at the corresponding position as the target. //1// for the //absolute left//, //2// for the //middle// object, and //3// for the object on the //absolute right//. If the capture condition for any of the targets is satisfied, the players gains one extra score point, and then the target is thrown up at a random position with random speed to start again.

The targets are caught. if (**target1_mc._y>250** and **player_mc.myPosition == 1** ){ score++; target1_mc._y =-random(40); target1_mc.speed= random(score)+4; } if (**target2_mc._y>250** and **player_mc.myPosition == 2** ){ score++; target2_mc._y =-random(40); target2_mc.speed= random(score)+4; } if (**target3_mc._y>250** and **player_mc.myPosition == 3** ){ score++; target3_mc._y =-random(40); target3_mc.speed= random(score)+4; }

Our final task is to check for **Game Over**, if the number of lives reaches zero, then we have to remove all of our targets from the stage and then go to and stop at the Game Over Frame - ie //Frame 5//.// Game Over

if (**lives == 0**){ removeMovieClip("target1_mc"); removeMovieClip("target2_mc"); removeMovieClip("target3_mc"); gotoAndStop(5); }

We only need to remove objects we created dynamically via ActionScript as those will not be removed when you leave the frame that contains them. The player movie clip does not have to be removed because it is an actual object on the stage and it will not be visible once we leave the frame that contains it.

The loop 2 (Frame 4)
That completes our game engine, but if you noticed, this was all just one frame and to make it loop we will add this code to the //next frame//, //Frame 4// in the //Actions// layer.

Plays the previous frame gotoAndPlay(3);

Our Game loop is done, here is what we did here:// //The very last frame, **Game Over Frame**, is next.//
 * 1) //Added a button to the// Buttons //layer and configured the key controls.//
 * 2) //Assigned the// Actions //to make the targets move.//
 * 3) //Assigned the// Actions //to determine what happens when the targets reach the ground.//
 * 4) //Assigned the// Actions //to determine what happens when the targets are captured.//
 * 5) //Assigned the// Actions //to determine what happens when all the lives are consumed.//
 * 6) //Assigned the// Actions //to make// Frame 4 //loop with// Frame 3//. (Game Execution loop).//

=//Step 5 - Game Over Frame//= //The player will be directed to the **Game Over Frame** if he loses all his lives. The Game Over screen will display the final score achieved and will give the player the option to play the game once more. This means that we will have to put some static text, dynamic text to display the score, and a button to make key commands to restart the game. We will do these from the bottom up.//

//Adding Text//
//Select the// Main Content //layer and use the// Text Tool //to write// YOUR SCORE IS //at the upper part of the stage and then write// PLAY AGAIN? //at the lower section of the stage as illustrated in the image below. You will have to make sure that the type of both of these texts is// static //(check the// Properties Inspector//).//

Displaying the Score
To display the actual score on the screen, we need to use a Dynamic Text Field//. Make sure that nothing on stage is selected, select the// Text Tool//, and then access the// Properties Inspector //and assign the// Text Type //to// Dynamic Text //to be able to draw such a text field. Now draw a big rectangular field between the two lines of text you have on stage. While your text field is still selected, set the size to// 80px//, the font to// _sans//,// center //the text, and then assign the variable name// score //to it.//

Adding Key Controls
To register the key command for the game to be played again would require us to create a button the same way we did for the previous commands. Select the Buttons //layer, open up the// Library //(//Ctrl+L//) and drag a copy of the// myButton //symbol we created previously. Put it somewhere above the stage. Now right-click this button and select// Actions //to open up the// Actions //panel. Type this code to make the game play once again when pressing the// Enter //button. The code is self-explanatory. Frame// 2 //is the **Intialization** Frame which sets all the variables and objects required to start the game, the game will follow from there automatically.//

//on (keyPress ""){// //gotoAndPlay(2);// //}//

//We are done! In this final stage you did the following:// We are done. You can now test your movie or export it to try it on your mobile device. The game we created here is a very basic one, play around with symbols and scripts to see what you can do. Have fun!
 * 1) //Added the Game Over text to the// Main Content //layer.//
 * 2) //Added the// Score //display text field to the// Main Content //layer.//
 * 3) //Added a button to the// Buttons// layer and configured the key controls to go back and play the game.