Flash AS3 Tutorial: Random Puzzle Effect

Tutorials No Comments

Recently we got quite a few questions about how the random puzzle animation (if you scroll through months) on our WordPress Calendar is made. Some people found it really cool and so we decided to make a tutorial about it. As you will soon see, implementation is fairly easy and doesn’t require a lot of coding. Instead of calendar days we will use puzzle pieces that will come together with a random animation. We used a puzzle piece that can be found on ShutterStock. Please note that vector is not available in source files (only png file is) and that if you wish to use it you will have to buy it.

[kml_flashembed publishmethod=”static” fversion=”9.0.0″ movie=”  http://premiumcoding.com/wp-content/uploads/2011/09/PuzzleEffect.swf ” width=”570″ height=”570″ targetclass=”flashmovie”]
Get Adobe Flash player
[/kml_flashembed]
 
Download Flash AS3 Tutorial: Random Puzzle Effect Source (2090)

STEP 1: IMPORTING ASSETS TO FLASH

Now that we have all the necessary assets open Flash and make a new document in AS3. Go to Modify/Document and set dimensions of the stage to 570px width and 570px height. First we have to import our assets into library. Go to File/Import/Import to Library and import puzzleIcon.png that you can find in source files. Go to Window/Library to bring up the library tag.It is time to convert them to MovieClips so we can interact with them with actionscript. Drag the icon to your stage, right click on it and select Convert to Symbol and name it puzzleIcon. Don’t forget to Export it for Actionscript (see screenshot below):

as3 export for actionscript

Now delete the icon from the stage. Repeat the process and import the shuffle button. Convert it to MovieClip and name it shufflePuzzles. In this case do not export it for actionscript and leave it on the stage. Name the instance of Movieclip (Window/Properties and then enter Instance name – shufflePuzzles).
[amazon_carousel widget_type=”SearchAndAdd” width=600″ height=”200″ title=”” market_place=”US” shuffle_products=”True” show_border=”False” keywords=”flash” browse_node=”” search_index=”Books” /]

STEP 2:  SETTING VARIABLES

First we have to import Tweenlite classes. Press F9 to bring actions menu and copy following code at the start of the document.


import com.greensock.*;
import com.greensock.easing.*;

First we have to define variables:

var puzzleHolder:Sprite = new Sprite();
var listOfPuzzles:Array = new Array();
var positionX:Array = new Array();
var positionY:Array = new Array();
var daysPosCounter:int = 0;
addChild(puzzleHolder);

puzzleHolder is a container in which all the created puzzles will be stored. ListOfPuzzles is an array that will also hold instances of each puzzle (we need this so we can interact with each puzzle after they are all stored in an array). Next two arrays (positionX and position) are crucial for random effect implementation. They will hold exact ending position of each puzzle. That means the position that each puzzle will take after animation is finished.

STEP 3:  PUZZLE FUNCTION

We can now start coding our main function that will take care of the random positioning at the beginning and then bring all pieces of puzzle together.  We will use two for loops (one to build rows and the second to build columns). Within the second loop we first define each puzzle from the puzzleIcon class that we defined earlier. We then apply random start positioning for each puzzle (both x and y coordinates). We will use our well known function getRandom that we already used in some of our previous tutorials. We will position our puzzle pieces randomly on the stage and their X and Y coordinates will be somewhere between -800 and 800. It is now time to set ending position for each puzzle piece and push those values to our two arrays. PositionX will hold all 100 values for X coordinate of each puzzle and position will do the same for y coordinate. Values -12 and -13 are used because we need to put puzzle pieces close together. To further clarify this please take a look at the screenshot below to see how the puzzle would look if we removed those values:

as3 puzzle difference width

We now add each puzzle to the Container and into an array. We will now add another for loop that will animate puzzle pieces to their ending positions (that we stored in positionX and positionY). To make the function a bit more realistic we will once again use function getRandom to set the time each puzzle piece animates across the stage. Function now looks like this:


function shufflePuzzle():void{
for (var i:int = 1; i <= 10; i++) {
for (var j:int = 1; j <= 10 ; j++) {
var puzzle:puzzleIcon = new puzzleIcon();
puzzle.x =getRandom(-800, 800);//position of buttons that hold days
puzzle.y =getRandom(-800, 800);
positionX[daysPosCounter] = (puzzle.width -12) * (j – 1) + 95;
positionY[daysPosCounter] = (puzzle.height-13) * (i-1) + 70;
daysPosCounter++;
puzzleHolder.addChild(puzzle);
listOfPuzzles.push(puzzle);
}
}

for (var k:int = 0; k < 100; k++)
TweenLite.to(listOfPuzzles[k],getRandom(2,4), {x:positionX[k],y:positionY[k],ease:Back.easeOut});
}


Execute the function with following call:

shufflePuzzle();

Animation now executes once. We will now implement a button that will repeat the animation on click. Add following code:

shufflePuzzles.buttonMode = true;
shufflePuzzles.useHandCursor = true;
shufflePuzzles.mouseChildren = false;
shufflePuzzles.addEventListener(MouseEvent.CLICK, startShuffling);

We added event listener that calls function startShuffling on MouseClick. Purpose of this function is to first remove all puzzle pieces from our container and array and then call function shufflePuzzle that once again starts our animation.

function startShuffling(e:MouseEvent){
for (var j:uint = puzzleHolder.numChildren; j > 0; j–){
puzzleHolder.removeChildAt(j-1);
listOfPuzzles.pop();
}
shufflePuzzle();
}

All we have to add now is function getRandom that returns a random value between two specified values (for instance between -800 and 800).

function getRandom(min:Number, max:Number):Number {
return min + (Math.random() * (max – min));
}

EASINGS

You can play with easings a bit to achieve some funny effects. Take a look at how this puzzle animation looks with Elastic easing:

[kml_flashembed publishmethod=”static” fversion=”9.0.0″ movie=”  http://premiumcoding.com/wp-content/uploads/2011/09/PuzzleEffectElastic.swf ” width=”570″ height=”570″ targetclass=”flashmovie”]
Get Adobe Flash player
[/kml_flashembed]

CONCLUSION

And so our puzzle tutorial comes to an end. As you can see implementation is really simple and you can use the idea for various purposes. Hopefully you can put your new knowledge to good use. Enjoy.

Download Flash AS3 Tutorial: Random Puzzle Effect Source (2090)
We really appreciate you for visiting PremiumCoding and reading this article! Now you might also want to check out our Themes here.
PremiumCoding
Written by PremiumCoding
We develop beautiful Wordpress themes with minimal and clean design.