Mar 12, 2012
Posted on Mar 12, 2012 in Hints and Tips | 10 comments
In this tutorial you’ll learn how to create a spinning wheel using Flash and AS3, with an interface that’s suitable for both mouse- and touch-based devices.
Final Result Preview
Let’s take a look at the final result we will be working towards:
Click and drag your mouse vertically to spin the wheel; the longer the line you drag, the faster the wheel will spin! Once it stops, the colored bar at the bottom will display the color the wheel landed on.
Step 1: Brief Overview
Using pre-made graphic elements we’ll create a colorful interface that will be powered by several ActionScript 3 classes.
The user will be able to spin the wheel using a dragging gesture represented by a line on the screen; a taller line will make a faster spin.
Step 2: Flash Document Settings
Open Flash and create a 500x300px document. Set the frame rate to 24fps.
Step 3: Interface
A colorful nice looking interface will be displayed, made up of multiple shapes, MovieClips and more.
The simple shapes were created using the Flash Pro drawing tools, and since they’re easy to duplicate I won’t explain their creation. Make sure the wheel’s rotation point is in the center.
You can always look at the FLA in the source download files.
Step 4: Instance Names
The image above shows the Instance Names of the various MovieClips. Pay special attention to the wheel.p MovieClips; these are the little black lines that divide the colors in the wheel, and are inside the wheel MovieClip. They are named p1 to p10, going clockwise.
Step 5: TweenMax
We’ll use a different tween engine than the default one included in Flash; this will make the color transition of the colorMC symbol a lot easier.
You can download TweenMax from the Greensock website.
Step 6: Set Main Class
Add the class name, Main, to the Class field in the Publish section of the Properties panel to associate the FLA with the Main document class.
Step 7: Create a new ActionScript Class
Create a new (Cmd + N) ActionScript 3.0 Class and save it as Main.as in your class folder.
Step 8: Class Structure
Create your basic class structure to begin writing your code.
package
{
import flash.display.Sprite;
public class Main extends Sprite
{
public function Main():void
{
// constructor code
}
}
}
Step 9: Required Classes
These are the classes we’ll need to import for our class to work. The import directive makes externally defined classes and packages available to your code.
import flash.display.Sprite;
import flash.display.Shape;
import flash.events.MouseEvent;
import flash.events.Event;
import com.greensock.TweenMax;
Step 10: Variables
These are the variables we’ll use; read the comments in the code to know more about them:
private var speed:Number = 0; //the current speed of the wheel
private var paddles:Vector.<Sprite> = new Vector.<Sprite>(); //a vector that holds the p1, p2 etc MCs in the stage
private var line:Shape; //the line drawn as the gesture to move the wheel
private var lastPaddle:String; //will detect the current value of the wheel
Step 11: Constructor
The constructor is a function that runs when an object is created from a class, and is the first to execute when you make an instance of an object. Since this is our document class, it’ll run as soon as the SWF loads.
public final function Main():void
{
//code...
}
Step 12: Paddles Vector
First we add the various paddle MovieClips to the vector, and add the listeners – we’ll write the listeners() function next.
public final function Main():void
{
paddles.push(wheel.p1, wheel.p2, wheel.p3, wheel.p4, wheel.p5, wheel.p6, wheel.p7, wheel.p8, wheel.p9, wheel.p10);
listeners('add');
}
Step 13: Listeners
This function will add or remove the listeners according to the parameter. Mouse Listeners are set to draw the line that will control the wheel.
private final function listeners(action:String):void
{
if(action == 'add')
{
stage.addEventListener(MouseEvent.MOUSE_DOWN, startDraw);
stage.addEventListener(MouseEvent.MOUSE_UP, spinWheel);
}
else
{
stage.removeEventListener(MouseEvent.MOUSE_DOWN, startDraw);
stage.removeEventListener(MouseEvent.MOUSE_UP, spinWheel);
}
}
Step 14: Movement Line
The next function starts to create a line based on the current mouse position, and places it on the stage. It’s triggered when the mouse is clicked.
private final function startDraw(e:MouseEvent):void
{
line = new Shape();
addChild(line);
line.graphics.moveTo(mouseX, mouseY);
line.graphics.lineStyle(8, 0x000000, 0.3);//you can change the line color and style here
stage.addEventListener(MouseEvent.MOUSE_MOVE, drawLine);
}
Step 15: Draw Line
While the mouse is moved, the line continues in that direction.
private final function drawLine(e:MouseEvent):void
{
line.graphics.lineTo(mouseX, mouseY);
}
Step 16: Spin the Wheel
The next code runs when the mouse button is released, finishing the line. The drawing listeners are removed to avoid drawing multiple lines and the speed is calculated according to the height of the line. Finally, an EnterFrame event is called to actually rotate the wheel.
private final function spinWheel(e:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_MOVE, drawLine);
listeners('rm');
speed = line.height * 0.1;
removeChild(line);
line = null;
stage.addEventListener(Event.ENTER_FRAME, spin);
}
Step 17: Rotate the Wheel
This is the function that will spin the wheel and detect what value it lands on:
private final function spin(e:Event):void
{
/* Rotate Wheel */
wheel.rotationZ += speed;
Step 18: Detect Value
Here we detect the current value of the wheel based on the last paddle it touched.
/* Detect Value */
for(var i:int = 0; i < 10; i++)
{
if(indicator.hArea.hitTestObject(paddles[i]))
{
lastPaddle = paddles[i].name;
}
}
Step 19: Decrease Speed
The wheel’s speed is reduced every frame to eventually stop the spinning.
/* Decrease speed */
speed -= 0.1;
Step 20: Reset Wheel
All values are reset when the wheel stops. A function that will run an action according to the final value is called.
/* Remove listener and reset speed when wheel stops */
if(speed <= 0)
{
stage.removeEventListener(Event.ENTER_FRAME, spin);
speed = 0;
setBarColor(lastPaddle);
listeners('add');
}
}
Step 21: Set Bar Color
This function will run a custom action according to the last value of the wheel. In this case it changes the color of the bottom bar, but you could make it do anything else.
function setBarColor(action:String):void
{
switch(action)
{
case 'p1':
TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0xF15D5D, tintAmount:1}});
break;
case 'p2':
TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0xC06CA8, tintAmount:1}});
break;
case 'p3':
TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0x644D9B, tintAmount:1}});
break;
case 'p4':
TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0x5E98C6, tintAmount:1}});
break;
case 'p5':
TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0x4789C2, tintAmount:1}});
break;
case 'p6':
TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0x55C4CB, tintAmount:1}});
break;
case 'p7':
TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0x57BC80, tintAmount:1}});
break;
case 'p8':
TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0x90CC6C, tintAmount:1}});
break;
case 'p9':
TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0xEBE666, tintAmount:1}});
break;
case 'p10':
TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0xF29C69, tintAmount:1}});
break;
}
}
Conclusion
Change the code to perform your own actions!
I hope you liked this tutorial, thank you for reading!



View full post on Activetuts+
Mar 10, 2012
Posted on Mar 10, 2012 in Hints and Tips | 10 comments
Flash games are very much the bread and butter of indie pop-nerd culture. If you consider the slices of bread the menu and the game itself, what is left? The butter – the very substance that makes the bread taste that much more delicious. And in terms of a Flash game, what comes in between menus and games are the transitions!
Final Result Preview
This is an example pattern of the transition effect that we will be working towards:
Step 1: Setting Up
Per usual we need to create a new Flash File (ActionScript 3.0). Set its width to 400px, its height to 200px, and the frame rate to 30fps. The background color can be left as the default. Save the file; it can be named whatever you please. I named mine Transitions.fla.
Next we need to create a document class. Go to your Flash file’s properties and set its class to Transitions. Then create the document class:
package {
import flash.display.*;
import flash.events.*;
public class Transitions extends MovieClip {
static public var val:Number = new Number();
static public var transitionAttached:Boolean = new Boolean();
public function Transitions() {
val = 0;
transitionAttached = false;
}
}
}
The code just introduced two variables. The first will be used to select the effect’s pattern, and the second will be used to check against having multiple instances of the effect on the stage.
Step 2: Creating the Square Sprite
Our next step is to create the sprite that will be used as each square for the transition. Create a new class and save it as Square.as:
package{
import flash.display.*;
import flash.events.*;
public class Square extends Sprite{
public var squareShape:Shape = new Shape();
public function Square(){
}
}
}
We use the squareShape variable to draw our shape inside the Sprite. Draw a rectangle 40px by 40px (Which is the full size) and set its scale to 0.1, a tenth of its size – this will aid us in the effect later:
addChild(squareShape);
squareShape.graphics.beginFill(0x000000,1);
squareShape.graphics.drawRect(-20,-20,40,40);
squareShape.graphics.endFill();
this.scaleX = 0.1;
this.scaleY = 0.1;
Step 3: Creating the Effect
Create another new class for the effect itself. Once we are finished, adding the effect to the stage will be very simple:
package{
import flash.display.*;
import flash.events.*;
import flash.utils.*;
public class FadeEffect extends Sprite{
public var currentFadeOut:int = 00;
public var currentSquares:int = 01;
public var pauseTime:int = 01;
public var tempNum:int = 00;
public var fading:String = "in";
public var fadeinTimer:Timer = new Timer(100);
public var fadeoutTimer:Timer = new Timer(100);
public var fadeArray:Array = [
//top
[[01,01,01,01,01,01,01,01,01,01],
[02,02,02,02,02,02,02,02,02,02],
[03,03,03,03,03,03,03,03,03,03],
[04,04,04,04,04,04,04,04,04,04],
[05,05,05,05,05,05,05,05,05,05]],
//bottom
[[05,05,05,05,05,05,05,05,05,05],
[04,04,04,04,04,04,04,04,04,04],
[03,03,03,03,03,03,03,03,03,03],
[02,02,02,02,02,02,02,02,02,02],
[01,01,01,01,01,01,01,01,01,01]]];
public var squaresArray:Array = new Array();
public function FadeEffect(){
}
}
}
You are probably thinking “that is a heck of a lot of variables, what all are they used for?”:
currentFadeOut - used as a check for tempNum to see how many squares are to be scaled
currentSquares - the current value indicating which squares should be attached and/or scaled
pauseTime - a simple integer to give a slight pause in between transitions and removing itself
tempNum - used to check what numbers in the array are to be scaled
fading - a string to check if the transition is fading in or out
fadeinTimer - a timer that is called to begin the fading in of the current value of currentSquares
fadeoutTimer - another timer that is called to begin the fading out of the current value of currentSquares
fadeArray - the 3D array that contains all the transition patterns
squaresArray - an array for the Square sprites
Our effect will begin by initiating an event listener for fadeInTimer and starting it. We also need to add an event listener to continuously scale all of the sprites to their correct sizes. Use the following code inside the constructor:
fadeinTimer.addEventListener("timer", fadeSquaresInTimer);
fadeinTimer.start();
addEventListener(Event.ENTER_FRAME, enterFrame);
The next step is to create those two event listeners. We will start with the easier of the two, the enterFrame function:
public function enterFrame(e:Event){
for each(var s1 in squaresArray){
tempNum+=1;
if(fading=="in"){
if(s1.scaleX<=1){
s1.scaleX+=0.05;
s1.scaleY+=0.05;
}
}else if(fading=="out"){
if(tempNum<=currentFadeOut){
if(s1.scaleX>=0.1){
s1.scaleX-=0.05;
s1.scaleY-=0.05;
}else{
if(s1.visible == true){
s1.visible = false;
}
}
}
}
}
tempNum=00;
}
It may not make total sense right now, but this should help shed some light.
s1 is the instance name that will be given to the Squares when we create them in a later function.
- They are added to an array called
squaresArray to keep track of the number of them and we perform the same operation for every object in the array.
- Next we increase
tempNum (used in the fading out if-statement) which is used to scale the sqaures in the order that they were added to the array. This means it is not pattern dependant and will work with any pattern.
After that…
- We check if
fading is true or not.
- If true, it scales all the squares up until they reach their full size (they begin scaling immediately after currentSquares increases).
- Once it begins fading out things become a little trickier; we only scale down the squares that are lower than the current value of
currentFadeOut (these are the ones that should be scaling, all others should remain at full scale until the value increases).
- Once they have scaled down to a tenth of the size we make those squares invisible (they will be deleted with the whole effect).
It’s time to add the event listener for the timer:
public function fadeSquaresInTimer(e:Event){
fadeSquaresIn(fadeArray[Transitions.val]);
currentSquares+=1;
}
At first glance it looks less complicated, but you should notice that we are calling a function with the fadeArray as the parameter. Which pattern is selected from the array depends on what you set val equal to in the Transitions class; right now it should use the first pattern because val is set to 0.
The next step is to create the fadeSquaresIn function that is called from the previous timer:
public function fadeSquaresIn(s:Array){
for (var row=0; row<s[0].length; row++) {
for (var col=0; col<s.length; col++) {
}
}
}
First thing that we accomplish is iterating through the selected pattern. We start at row 1, colomn 1 and cycle through every colomn until the end of the row has been reached. Then we move onto the next row and repeat the process.
The next thing to do is compare the current item in the array to the value of currentSquares:
if(int(s[col][row]) == currentSquares){
}
If they are equivalent we add a square, position it accordingly, and push it onto the squaresArray so that it can be scaled:
var s1:Sprite = new Square();
s1.x = 20+(row*40);
s1.y = 20+(col*40);
addChild(s1);
squaresArray.push(s1);
We are almost done with this function, we just have to perform a check for when there are the same number of squares as there are items in the pattern. We do so by adding the following if-statement outside both for-loops:
if(squaresArray.length == (s[0].length * s.length)){
fadeinTimer.stop();
addEventListener(Event.ENTER_FRAME, pauseBetween);
}
Self explanatory – we stopped the timer and called an event listener for the pause between fading in and fading out. That function is used to initiate the fading out and may also be used to cause change in your game:
public function pauseBetween(e:Event){
pauseTime+=1;
if(pauseTime==60){
currentSquares=01;
fading="out";
fadeoutTimer.addEventListener("timer", fadeSquaresOutTimer);
fadeoutTimer.start();
removeEventListener(Event.ENTER_FRAME, pauseBetween);
}
}
We won’t spend much time on this function due to its simplicity. Here we increase the value of pauseTime, and once it equals 60 (meaning two seconds have passed) we set the value of currentSquares back to 1, set fading to "out" so that the squares can scale backwards, remove the listener for pauseBetween() itself, and add an event listener for this new function:
public function fadeSquaresOutTimer(e:Event){
fadeSquaresOut(fadeArray[Transitions.val]);
currentSquares+=1;
}
This works much like fadeSquaresInTimer(), though this time we are calling the function fadeSquaresOut():
public function fadeSquaresOut(s:Array){
for (var row=0; row<s[0].length; row++) {
for (var col=0; col<s.length; col++) {
if(int(s[col][row]) == currentSquares){
currentFadeOut+=1;
}
}
}
}
We cycle through, but this time when we find an equivalent item we increase the value of currentFadeOut so that the next item in the squaresArray can begin fading out.
Almost finished now; all that’s left is to stop the timer and remove the effect. Add this if-statement outside of the two for-loops:
if(currentFadeOut == (s[0].length * s.length)){
fadeoutTimer.stop();
pauseTime=01;
addEventListener(Event.ENTER_FRAME, delayedRemove);
}
This checks whether all of the items have begun fading out. If so, it then stops the timer, sets pauseTime back to 1 and adds an event listener for the function delayedRemove():
public function delayedRemove(e:Event){
pauseTime+=1;
if(pauseTime==30){
Transitions.transitionAttached = false;
removeEventListener(Event.ENTER_FRAME, delayedRemove);
stage.removeChild(this);
}
}
Like before we increase the value of pauseTime, and once it equals 30 (1 second) we set the boolean back to false so that the effect can be added once again. We remove this event listener and we remove this effect from the stage.
Step 4: Adding the Effect
Now comes the easy part. Add the following code inside the document class constructor to add the effect:
if(transitionAttached == false){
transitionAttached = true;
var f1:Sprite=new FadeEffect;
stage.addChild(f1);
}
Step 5: Creating More Patterns
Feel free to create your own patterns! It’s extremely simple, just create a new 2D array inside the 3D array. Here is the array that I have created (just replace your 3D array with it). It includes 8 different transitions:
[//top
[[01,01,01,01,01,01,01,01,01,01],
[02,02,02,02,02,02,02,02,02,02],
[03,03,03,03,03,03,03,03,03,03],
[04,04,04,04,04,04,04,04,04,04],
[05,05,05,05,05,05,05,05,05,05]],
//bottom
[[05,05,05,05,05,05,05,05,05,05],
[04,04,04,04,04,04,04,04,04,04],
[03,03,03,03,03,03,03,03,03,03],
[02,02,02,02,02,02,02,02,02,02],
[01,01,01,01,01,01,01,01,01,01]],
//left
[[01,02,03,04,05,06,07,08,09,10],
[01,02,03,04,05,06,07,08,09,10],
[01,02,03,04,05,06,07,08,09,10],
[01,02,03,04,05,06,07,08,09,10],
[01,02,03,04,05,06,07,08,09,10]],
//right
[[10,09,08,07,06,05,04,03,02,01],
[10,09,08,07,06,05,04,03,02,01],
[10,09,08,07,06,05,04,03,02,01],
[10,09,08,07,06,05,04,03,02,01],
[10,09,08,07,06,05,04,03,02,01]],
//top-left
[[01,02,03,04,05,06,07,08,09,10],
[02,03,04,05,06,07,08,09,10,11],
[03,04,05,06,07,08,09,10,11,12],
[04,05,06,07,08,09,10,11,12,13],
[05,06,07,08,09,10,11,12,13,14]],
//top-right
[[10,09,08,07,06,05,04,03,02,01],
[11,10,09,08,07,06,05,04,03,02],
[12,11,10,09,08,07,06,05,04,03],
[13,12,11,10,09,08,07,06,05,04],
[14,13,12,11,10,09,08,07,06,05]],
//bottom-left
[[05,06,07,08,09,10,11,12,13,14],
[04,05,06,07,08,09,10,11,12,13],
[03,04,05,06,07,08,09,10,11,12],
[02,03,04,05,06,07,08,09,10,11],
[01,02,03,04,05,06,07,08,09,10]],
//bottom-right
[[14,13,12,11,10,09,08,07,06,05],
[13,12,11,10,09,08,07,06,05,04],
[12,11,10,09,08,07,06,05,04,03],
[11,10,09,08,07,06,05,03,03,02],
[10,09,08,07,06,05,04,03,02,01]]];
You can change the value of Transitions.val to choose another pattern – for example, if val is 3, the transition will sweep in from the right.
Conclusion
Thanks for taking the time to read this tutorial. If you have any questions please leave a comment below. And if you would like a challenge, try making the effect fade in with one pattern and fade out with an opposing one.



View full post on Activetuts+
Feb 22, 2012
Posted on Feb 22, 2012 in Hints and Tips | 10 comments
First impressions are very important on a Flash game portal; if your game doesn’t grab the player in the first few seconds, they’ve got plenty of other games to choose from. As the menu is the first point of interface, anything you can do to make it less dull will help. In this tutorial we will create a menu that incorporates swapping depth, smooth roll over effects, and two different transition designs.
Final Result Preview
These are the two designs we will be working towards:
The first design will have the next screens transitioning in from different directions, depending on which option is clicked.
The second design transitions all screens in from the bottom: a more flexible choice if you have more than four options.
Introduction: What Makes It “Active”?
There are two main things that make this menu “active”. The first is the roll over effects on the buttons: regardless of how much they have scaled when you roll out ,they scale down from that particular size (unlike a tween created on the timeline). The second is that the code of the second style is designed to be flexible and easy to extend for your own needs.
Step 1: Setting Up
The first thing we are going to need to create is a new Flash File (ActionScript 3.0). Set its width to 600px, its height to 300px, and the frames per second to 30. The background color can be left as white.
Now save the file; you can name it whatever you please, but I named mine menuBounce.fla.
In the next section we will create the eight MovieClips used in the menu. For reference, here is a list of all the colors used throughout the tutorial:
- White – #FFFFFF (
0xffffff)
- Gold – #E8A317 (
0xe8a317)
- Light Gold – #FBB917 (
0xfbb917)
- Blue – #1569C7 (
0x1569c7)
- Light Blue – #1389FF (
0x1389ff)
- Green – #347235 (
0x347235)
- Light Green – #3E8F1B (
0x3e8f1b)
- Red – #990000 (
0x990000)
- Light Red – #C10202 (
0xc10202)
- Matte Grey – #222222 (
0x222222)
Step 2: Creating the MovieClips
To begin with we’ll create the “backs” (the movie clips that will stand in for actual screens), but before we begin let’s turn on some very useful Flash features.
Right-click the stage and select Grid > Show Grid. By default it will create a 10px by 10px grid across the stage. Next, right-click the stage again and this time select Snapping > Snap to Grid.
Now we can start drawing! Select the Rectangle Tool and draw a 600x300px light gold rectangle. Then select this fill, right-click and choose Convert to Symbol. Name the MovieClip goldBack, set the type to MovieClip and the registration to top-left.
Next right-click the MovieClip and select Duplicate three times to make three more copies of it. Now recolor them with light blue, light green and light red. Then name them blueBack, greenBack and redBack, respectively.
To finish off the backs we should add some sort of text inside each MovieClip: on goldBack write “PLAY”, on blueBack write “INSTRUCTIONS”, on greenBack write “OPTIONS”, and on redBack write “CREDITS”. Once you have written the text I would recommend breaking it apart until it becomes a fill (this removes the need to embed fonts and makes the transition look smoother). Your backs should look similar to the one below:
Now let’s start on the clickable squares! Select the Rectangle Tool and draw a 100x100px light gold square. Select the fill, right-click and Convert to Symbol. Name the MovieClip goldSquare, set the type to MovieClip and the registration to top-left. Now is the time to write text on the square, except this time instead of breaking the text apart leave it for now. Insert a keyframe and change the fill color to gold. Now break apart the text on both frames until they become fills.
Now right-click the MovieClip and choose Duplicate Symbol three times. Then repeat the same process from before for the other three colors, naming the MovieClips blueSquare, greenSquare and redSquare, respectively. Your squares should look similar to the one below:
Step 3: Positioning the MovieClips
Begin by deleting everything off the stage. Then go to Insert > New Symbol. Name it menuBounceMC, set the type to MovieClip, the registration to the top-left and export it as MenuBounceMC.
Now drag all the backs from the library into it and position them in the following way:
- goldBack: (-600,0)
- blueBack: (0,-300)
- greenBack: (0,300)
- redBack: (600, 0)
If you are going to use the one direction design then position all four of the backs at one of those positions. I used (0, 300).
Now drag all of the squares from the library into the MovieClip and positon them in the following way:
- goldSquare: (120,150)
- blueSquare: (240,150)
- greenSquare: (360,150)
- redSquare: (480, 250)
The last thing we have to do before we begin coding is assign the instance names. Set the instance names for the squares as square0, square1, square2, square3, starting from the left. Next set the instance names for the backs according to the corresponding with the square of the same color. So goldBack would get the instance name back0 because the goldSquare has the instance name square0.
Step 4: Setting Up the Classes
Now that we are finished creating and positioning the MovieClips we can begin to set up the two classes that we will use.
First go to your Flash file’s Properties and set its class to MenuBounce; then, create a new ActionScript 3.0 file and save it as MenuBounce.as.
Now copy the following code into it; I will explain it after:
package{
import flash.display.MovieClip;
import flash.events.Event;
public class MenuBounce extends MovieClip{
public var menuBounceMC:MenuBounceMC = new MenuBounceMC();
public function MenuBounce(){
addChild(menuBounceMC);
}
}
}
This is a basic document class to which we’ve added a little extra code that creates an instance of MenuBounceMC and adds it to the stage.
Now create a new ActionScript 3.0 file and save it as MenuBounceMC.as. Now copy the following code into it so we can set it up.
package{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class MenuBounceMC extends MovieClip{
public var activeSquare:MovieClip;
public var activeBack:MovieClip;
public var squaresArray:Array = new Array();
public var backsArray:Array = new Array();
public var speed:Number = 20;
public function MenuBounceMC(){
}
}
}
Each variable has a specific purpose:
activeSquare: Which square is being rolled over
activeBack: Which back has been selected to move
squaresArray: An array containing all of the square MovieClips
backsArray: An array containing all of the back MovieClips
speed: How many pixels the backs are moved by every frame
All of those variables have been set, with the exception of topSquare (which is set in other functions) and the arrays. So we must push all of the MovieClips onto the array. Add the following lines inside the constructor:
squaresArray = [square0, square1, square2, square3];
backsArray = [back0, back1, back2, back3];
However this method can be a little bit tedious if you are going to use a high number of MovieClips in the menu – say 50. An alternative would be to create the MovieClips completely through code and push them when you add them to the menu. But for our purpose of using only eight MovieClips it works fine.
The last set of things we need to add to complete the setup is our event listeners, which will trigger all of the transitions and roll over effects. Add these lines below the push() lines.
addEventListener(MouseEvent.MOUSE_OVER, bounceOver);
addEventListener(MouseEvent.MOUSE_OUT, bounceOut);
addEventListener(MouseEvent.CLICK, bounceClick);
addEventListener(Event.ENTER_FRAME, bounceUpdate);
Step 5: Creating the MouseEvent Handlers
Let’s start off by creating the three easier functions:
public function bounceOver(event:MouseEvent):void {
}
public function bounceOut(event:MouseEvent):void {
}
public function bounceClick(event:MouseEvent):void {
}
Inside the bounceOver() function start by adding an if-statement to make sure that no back is currently “active” – that is, transitioning in, transitioning out, or sitting on top:
if(activeBack == null){
}
The remainder of all the code in the bounceOver() function will be written inside that if-statement. Now we figure out whether the object rolled over (the event.target) is a square, by checking whether it’s in the squaresArray[]:
if(squaresArray.indexOf(event.target) != -1){
}
Assuming it is, we do real meat of the function:
activeSquare = event.target as MovieClip;
activeSquare.gotoAndStop(2);
setChildIndex(activeSquare, numChildren - 1);
First we set the variable activeSquare to point to the square in question. After that, we pause this square’s animation on the second frame, which displays its “rollover” image. Lastly we move the sprite to be on top of everything else, using setChildIndex().
We now move into the bounceOut() function. This time, we start by checking whether the object from which the mouse is being rolled out is the currently active square:
if(event.target == activeSquare){
}
Inside the if-block add the following code; it pauses the square’s animation on the first frame again, and then sets activeSquare back to null so that we can roll over another:
activeSquare.gotoAndStop(1);
activeSquare = null;
Then go to the bounceClick() function. This function will be used to initiate all the transitions. Start off by checking whether there’s already an active back:
if(activeBack == null){
}
This prevents the user from clicking another square during a transition. If there is an active back, then a click should undo this, so that we can click another square:
if(activeBack == null){
}else{
activeBack = null;
}
Assuming there’s no currently active back, once again add an if-block to check whether the object clicked was a square:
if(activeBack == null){
if(squaresArray.indexOf(event.target) != -1){
}
}else{
activeBack = null;
}
If the user did click a square, we must set the corresponding back as the “active” back. Since the index of each item in backsArray[] matches the index of each item in squaresArray, this is simple:
if(activeBack == null){
if(squaresArray.indexOf(event.target) != -1){
activeBack = backsArray[squaresArray.indexOf(event.target)] as MovieClip;
}
}else{
activeBack = null;
}
Now we just need to move the currently active back so that it is on top of everything else:
if(activeBack == null){
if(squaresArray.indexOf(event.target) != -1){
activeBack = backsArray[squaresArray.indexOf(event.target)] as MovieClip;
setChildIndex(activeBack, numChildren - 1);
}
}else{
activeBack = null;
}
Step 6: Creating the Final Event Handler
This is the last function we are going to create. Let’s begin by adding the scaling effect for when a square is rolled over or out:
public function bounceUpdate(event:Event):void {
for each (var square in squaresArray) {
if(square == activeSquare){
if(square.scaleX <= 1.5){
square.scaleX +=0.05;
square.scaleY +=0.05;
}
}else{
if(square.scaleX >= 1){
square.scaleX -=0.05;
square.scaleY -=0.05;
}
}
}
}
Here, we’ve created a for-each loop to cycle through every square in the array and check whether it’s the currently active square. If it is, we scale it up until it is greater or equal to 1.5 times its regular size ; if it’s not, we scale it down until it’s back at its regular size. (Technically, this code could allow it to be very slightly smaller than its regular size, but this is unnoticeable in practice.)
Now this is where some of you will go your seperate ways; if you are creating Design 1 go to Step 7a, and if you are creating Design 2 go to Step 7b.
Step 7a: Finishing Design 1
Congratulations you have chosen design 1! This design is simple and easy to follow – assuming you have exactly four squares and backs. Any more, and it becomes a mess to maintain.
We’re going to use a long series of nested if-else statements – very messy, I know. But let me tell you the reasoning behind this! Each back has a different starting position and transition direction. In a nutshell, you can’t use a single for-loop to move all the MovieClips unless you have one if statement to check which back is moving, another to set the axis of movement (x or y), and a third to set the speed (positive or negative). Okay, we could store all this information in properties of the squares or something like that, but I think this is one approach where “Keep It Simple, Stupid” applies.
if(activeBack == back0){
if(back0.x < 0){
back0.x += speed;
}
}else{
if(back0.x > -600){
back0.x -= speed;
}
}
if(activeBack == back1){
if(back1.y < 0){
back1.y += speed;
}
}else{
if(back1.y > -300){
back1.y -= speed;
}
}
if(activeBack == back2){
if(back2.y > 0){
back2.y -= speed;
}
}else{
if(back2.y < 300){
back2.y += speed;
}
}
if(activeBack == back3){
if(back3.x > 0){
back3.x -= speed;
}
}else{
if(back3.x < 600){
back3.x += speed;
}
}
The code’s easy to understand; it looks at each back and moves it onto the stage or off the stage, in the correct direction, depending on whether or not it’s active.
Step 7b: Finishing Design 2
Congratulations you have chosen Design 2! This design is far more flexibile and makes things a lot easier in terms of adding more backs and using less code. For this design we will use another for-each loop to examine each back in the backsArray:
for each (var back in backsArray){
if(back == activeBack){
if(back.y > 0){
back.y -= speed;
}
}else{
if(back.y < 300){
back.y += speed;
}
}
}
Now this should be pretty easy to understand. It cycles through the backs and checks each to see whether it’s active. If it is, the code moves it upwards onto the stage, and stops moving it once it is completely on (i.e. once it’s at y=0 or higher). If the back isn’t active, the code moves it back down until it reaches its starting position.
Conclusion
Here’s a challenge: given 16 squares (and 16 backs), can you make it so that Squares 1, 5, 9, and 13 make the corresponding backs transition in from the left, Squares 2, 6, 10, and 14 make them transition in from the top, and so on? You’ll need to combine the two approaches, as well as check the position of the active square/back in its array.
Thanks for taking the time to read through this tutorial. I hope you enjoyed the finished product and learned something about making active, flexible menus!



View full post on Activetuts+