logo
468x60-2-495


  • Home
  • Privacy Policy
  • About
search
top
Sep 1, 2011 Posted on Sep 1, 2011 in Hints and Tips | 10 comments

Animate a Cartoon Explosion With Flash Professional

In this tutorial we’ll show you how to animate an awesome explosion in Flash, which you could use for an cartoony action game. We take you from conception to completion, then show you how to export it as well as how to import it into other scenes.


Final Result Preview

Let’s take a look at the final result we will be working towards:


Step 1: Choose the Type of Explosion You Would Like

Decide what kind of explosion would be best fitting for your scene. Is it a small explosion? A nuke? A 60′s Batman-esque, flashy, “WHAM”? In this case we will be doing a smaller explosion, but with experience you could do anything you want.

What you will be creating in this tutorial.

Step 2: Look for References

Once you know what you want to animate look for reference. The Internet is amazing for this because you can just search for movie clips related to what you’d like to do and carefully study them.

Searching for explosions on Youtube.

Step 3: Begin to Draw

Once you are ready grab a few pieces of paper and begin to draw your explosion. Animation is planned through keyframes, which are generally the most extreme parts of the animation which tell the rough story of how something is going to move. In this case, the first thing that you should be thinking about is the initial flash of light.

Drawing of the first frame of animation

Step 4: Draw All the Keyframes

Next, draw the keys explaining how the smoke and light comes out of the bomb. You will at the very least want one where the smoke is first coming out of the light, then one when the smoke is at its largest and most extreme, and then a frame at the end. Here are our keyframe drawings, which illustrate this process:

Drawing of all of the keyframes.

Step 5: Draw All the In-Betweens

Draw the in-betweens for these frames. Basically, you are now drawing all of the frames which fit in the middle of these keyframes. We will include our sketches here for reference.

Every single frame drawing.

Step 6: Scan Your Drawings

At this point we scan all of our drawings so that we can trace them in Flash.

A photo of a scanner.

Step 7: Change the Basic Flash Settings

Open Flash and change your settings to whatever would be the best fit for your current scene. You can see all of your basic settings in the properties panel on the right hand side of the screenshot. In our case, we will be working at 550x500px and 24 frames per second, with a white background.

The basic settings in Flash.

Step 8: Import Your Drawings

Next you should import all of your line drawings into Flash Pro’s Library. The Library is basically a place where all of the files that you are using in your animation are stored for safe-keeping. You can do this by going to File > Import > Import to Stage, then selecting all of your drawings and hitting Open.

After this they will appear all on the same keyframe, but if you select them all, right-click and hit “Distribute to Layers,” they will appear as seperate layers, all on the same keyframe. Then you can simply drag and drop individual keys into the right positions, either on their own layers on all on one layer, whichever you’d prefer.

Showing how to get to Flash's Library.

Step 9: Draw Your Initial Lines

Add a new layer to your timeline, then begin to draw over your old lines using the Line tool. We generally do not bother using the brush tool because you end up with too many nodes on the lines which can make things extremely difficult to change in any way later. What you will basically need to do is draw lines using the line tool, then use the selection tool to manipulate the curve between the two points. (More Flash drawing tips are available here.)

Showing me drawing and then manipluating a line.

Step 10: Convert Lines to Fills

Once the frame has been entirely traced with the line tool we select all of the lines, then go to Modify > Shape > Convert Lines to Fills. Occasionally there will be glitches where bits of the line disappear. If this happens then start off by selecting smaller chunks of the image, then eventually doing the whole graphic together. Once you do this you can then edit the line depth using the selection tool and clicking and dragging on the edges of lines.

Showing the Convert Lines to Fills Dialogue Box

Step 11: Color Your Drawings

Color in the lines using the paint bucket tool.

Paint Bucket Tool

Step 12: Finish All of the Frames of Animation

Repeat Steps 9-11 until all of the frames are finished.

Final Frame of Animation Completed

Step 13: Organize Your Animation

Select everything on a frame, hit F8 and turn it into a Symbol. Properly name it and it will appear in your library to be used and re-used at any time. Organization is really important while you’re animating. Things can get confusing fast if you don’t name and sort everything properly so please do so. You can even create folders in the library.

Showing the Convert to Symbol Dialogue

Step 14: Onion Skinning

One important tool which can really help you animate is the Onion Skin tool. With Onion Skinning you can easily view the frames closest to the one that you are editing so that you can tell right away if a piece of animation is going to work as planned or not. The Onion Skin button is located at the bottom of your timeline.

Onion Skin Tool

Step 15: Preview the Animation

To preview your full animation at any time, go to Control > Test Movie > Test. It will preload your whole animation and then show you exactly how it will look once exported.

Test Movie Dialogue

Step 16: Export the Movie

When you’re ready to export just go to File > Export > Export Movie. Name it whatever you’d like, pick .swf from the drop down menu, and then hit save. Depending on the size of your animation you may have to wait a short while.

Export Movie Dialogue

Step 17: Export as a GIF

Exporting .gif images is nearly the same. When you hit File > Export > Export Movie just pick .gif instead of .swf from the drop-down menu.

GIF Export Dialogue

Step 18: Import your Animation into an Existing Scene

To import an explosion into an already exisitng scene, first open both scenes. Then, select all of the frames of the explosion animation on the timeline, copy all of the frames, and then hit Ctrl + F8. A dialogue will appear. Name the explosion, then save it as a Graphic. Hit OK. A blank screen should appear with no animation on it. Then click on the first frame of the new timeline and paste all of your frames. After this hit the “Scene 1″ button under the timeline but above the animation window to go back to your original timeline. Once you do this your animation should be in the Library. Select your animation in the library, right click and copy it. You will then be able to paste it into the library of any other FLA that you have open.

A compilation of screengrabs related to the text.

Step 19: Create a Movie Clip

Making movie clips is almost the same as what we described in the previous step. To create a movie clip, follow the instructions from the last step exactly, but pick “Movie Clip,” instead of “Graphic,” when you reach the dialogue after hitting Ctrl + F8. The difference between a Graphic and a Movie Clip is that the Movie Clip can be uniquely identified using ActionScript, which is the coding language that Flash uses to make games and interactive media. When the movie is compiled a copy is created from the library and transformed for the animation. The copy can be blurred, scaled, etc., during runtime, without having to create separate animations at design time, thus cutting down on the amount of computer memory needed and keeping the SWF file size small.

Create New Symbol -- Movie Clip.

Step 20: Create a Sprite Sheet

To create a sprite sheet of your animation, first hit File > Export > Export Movie and select PNG sequence to create a set of PNG graphics, one for each frame. After they are created you can use any image editing software (such as Photoshop) to import them as a batch and then copy/paste them all into one larger image file.

Screenshot showing export as PNG

Alternatively, you could make your Flash scene larger, make each frame of animation appear at once, and then move the individual images into place before exporting a single image.

Example sprite sheet
Click to enlarge.

A third option is to use Keith Peters’s tool, SWFSheet.

The final result.

We hope you enjoyed this tutorial! If you make an explosion with it, please share it in the comments :)



View full post on Activetuts+

banner ad

10 Responses to “Animate a Cartoon Explosion With Flash Professional”

  1. Melissa and Jared Davidson says:
    September 1, 2011 at 5:33 pm

    In this tutorial we’ll show you how to animate an awesome explosion in Flash, which you could use for an cartoony action game. We take you from conception to completion, then show you how to export it as well as how to import it into other scenes.


    Final Result Preview

    Let’s take a look at the final result we will be working towards:


    Step 1: Choose the Type of Explosion You Would Like

    Decide what kind of explosion would be best fitting for your scene. Is it a small explosion? A nuke? A 60′s Batman-esque, flashy, “WHAM”? In this case we will be doing a smaller explosion, but with experience you could do anything you want.

    What you will be creating in this tutorial.

    Step 2: Look for References

    Once you know what you want to animate look for reference. The Internet is amazing for this because you can just search for movie clips related to what you’d like to do and carefully study them.

    Searching for explosions on Youtube.

    Step 3: Begin to Draw

    Once you are ready grab a few pieces of paper and begin to draw your explosion. Animation is planned through keyframes, which are generally the most extreme parts of the animation which tell the rough story of how something is going to move. In this case, the first thing that you should be thinking about is the initial flash of light.

    Drawing of the first frame of animation

    Step 4: Draw All the Keyframes

    Next, draw the keys explaining how the smoke and light comes out of the bomb. You will at the very least want one where the smoke is first coming out of the light, then one when the smoke is at its largest and most extreme, and then a frame at the end. Here are our keyframe drawings, which illustrate this process:

    Drawing of all of the keyframes.

    Step 5: Draw All the In-Betweens

    Draw the in-betweens for these frames. Basically, you are now drawing all of the frames which fit in the middle of these keyframes. We will include our sketches here for reference.

    Every single frame drawing.

    Step 6: Scan Your Drawings

    At this point we scan all of our drawings so that we can trace them in Flash.

    A photo of a scanner.

    Step 7: Change the Basic Flash Settings

    Open Flash and change your settings to whatever would be the best fit for your current scene. You can see all of your basic settings in the properties panel on the right hand side of the screenshot. In our case, we will be working at 550x500px and 24 frames per second, with a white background.

    The basic settings in Flash.

    Step 8: Import Your Drawings

    Next you should import all of your line drawings into Flash Pro’s Library. The Library is basically a place where all of the files that you are using in your animation are stored for safe-keeping. You can do this by going to File > Import > Import to Stage, then selecting all of your drawings and hitting Open.

    After this they will appear all on the same keyframe, but if you select them all, right-click and hit “Distribute to Layers,” they will appear as seperate layers, all on the same keyframe. Then you can simply drag and drop individual keys into the right positions, either on their own layers on all on one layer, whichever you’d prefer.

    Showing how to get to Flash's Library.

    Step 9: Draw Your Initial Lines

    Add a new layer to your timeline, then begin to draw over your old lines using the Line tool. We generally do not bother using the brush tool because you end up with too many nodes on the lines which can make things extremely difficult to change in any way later. What you will basically need to do is draw lines using the line tool, then use the selection tool to manipulate the curve between the two points. (More Flash drawing tips are available here.)

    Showing me drawing and then manipluating a line.

    Step 10: Convert Lines to Fills

    Once the frame has been entirely traced with the line tool we select all of the lines, then go to Modify > Shape > Convert Lines to Fills. Occasionally there will be glitches where bits of the line disappear. If this happens then start off by selecting smaller chunks of the image, then eventually doing the whole graphic together. Once you do this you can then edit the line depth using the selection tool and clicking and dragging on the edges of lines.

    Showing the Convert Lines to Fills Dialogue Box

    Step 11: Color Your Drawings

    Color in the lines using the paint bucket tool.

    Paint Bucket Tool

    Step 12: Finish All of the Frames of Animation

    Repeat Steps 9-11 until all of the frames are finished.

    Final Frame of Animation Completed

    Step 13: Organize Your Animation

    Select everything on a frame, hit F8 and turn it into a Symbol. Properly name it and it will appear in your library to be used and re-used at any time. Organization is really important while you’re animating. Things can get confusing fast if you don’t name and sort everything properly so please do so. You can even create folders in the library.

    Showing the Convert to Symbol Dialogue

    Step 14: Onion Skinning

    One important tool which can really help you animate is the Onion Skin tool. With Onion Skinning you can easily view the frames closest to the one that you are editing so that you can tell right away if a piece of animation is going to work as planned or not. The Onion Skin button is located at the bottom of your timeline.

    Onion Skin Tool

    Step 15: Preview the Animation

    To preview your full animation at any time, go to Control > Test Movie > Test. It will preload your whole animation and then show you exactly how it will look once exported.

    Test Movie Dialogue

    Step 16: Export the Movie

    When you’re ready to export just go to File > Export > Export Movie. Name it whatever you’d like, pick .swf from the drop down menu, and then hit save. Depending on the size of your animation you may have to wait a short while.

    Export Movie Dialogue

    Step 17: Export as a GIF

    Exporting .gif images is nearly the same. When you hit File > Export > Export Movie just pick .gif instead of .swf from the drop-down menu.

    GIF Export Dialogue

    Step 18: Import your Animation into an Existing Scene

    To import an explosion into an already exisitng scene, first open both scenes. Then, select all of the frames of the explosion animation on the timeline, copy all of the frames, and then hit Ctrl + F8. A dialogue will appear. Name the explosion, then save it as a Graphic. Hit OK. A blank screen should appear with no animation on it. Then click on the first frame of the new timeline and paste all of your frames. After this hit the “Scene 1″ button under the timeline but above the animation window to go back to your original timeline. Once you do this your animation should be in the Library. Select your animation in the library, right click and copy it. You will then be able to paste it into the library of any other FLA that you have open.

    A compilation of screengrabs related to the text.

    Step 19: Create a Movie Clip

    Making movie clips is almost the same as what we described in the previous step. To create a movie clip, follow the instructions from the last step exactly, but pick “Movie Clip,” instead of “Graphic,” when you reach the dialogue after hitting Ctrl + F8. The difference between a Graphic and a Movie Clip is that the Movie Clip can be uniquely identified using ActionScript, which is the coding language that Flash uses to make games and interactive media. When the movie is compiled a copy is created from the library and transformed for the animation. The copy can be blurred, scaled, etc., during runtime, without having to create separate animations at design time, thus cutting down on the amount of computer memory needed and keeping the SWF file size small.

    Create New Symbol -- Movie Clip.

    Step 20: Create a Sprite Sheet

    To create a sprite sheet of your animation, first hit File > Export > Export Movie and select PNG sequence to create a set of PNG graphics, one for each frame. After they are created you can use any image editing software (such as Photoshop) to import them as a batch and then copy/paste them all into one larger image file.

    Screenshot showing export as PNG

    Alternatively, you could make your Flash scene larger, make each frame of animation appear at once, and then move the individual images into place before exporting a single image.

    Example sprite sheet
    Click to enlarge.

    A third option is to use Keith Peters’s tool, SWFSheet.

    The final result.

    We hope you enjoyed this tutorial! If you make an explosion with it, please share it in the comments :)


  2. Michael James Williams says:
    September 1, 2011 at 6:13 pm

    Ready for another quiz? This month, it’s one for the Flash developers among you. Let’s see how well you know your Events…


    Let’s Get Quizzy


    Just So You Know…

    This quiz was built with the jQuizzy Quiz Engine by Siddharth, ace reviewer for Envato. jQuizzy is available for purchase over on Codecanyon :)



    Thanks also to Orman Clark and MediaLoot for their graphical contributions to the Activetuts+ Coffee Break Quizzes.


    What Would You Like To Be Tested On?

    If you’ve got an idea for an Activetuts+-related quiz subject, let us know in the comments!


  3. Collis says:
    September 1, 2011 at 6:33 pm

    It’s kinda crazy to think, but our little internet startup, Envato, has been on the air now for five years. We started back in 2006 as four very enthusiastic and totally green entrepreneurs with a shoestring budget and a love of the web. Fast forward five years and while we’re hopefully a little less green, we’re still incredibly passionate about Education, Marketplaces and the web! It’s been an amazing time and we’d like to share a look inside our Melbourne HQ offices, some stats about Envato and a big thank you to the community.

    Behind the Scenes

    With such a big milestone, we thought it might be good to give an inside glimpse into our Melbourne HQ offices and some of the people that work here. So we invited a Melbourne film crew called Compulsive to come in and shoot a 3 minute video about Envato. I hope you enjoy it!

    As you may know, we also have a large remote team working around the globe on our sites. Next year we’re hoping to gather all of Envato and as much of the community as possible for an epic meetup, but in the meantime if you’re curious to see who’s who, you can check out this little video from our remote staff meetup last year in Chicago.

    Some Stats

    Looking back at five years of exciting and sometimes exhausting Envato work, I put together some stats about Envato from our time online so far. In five years we have:

    • Published over 10,000 tutorials and articles helping people learn everything from Photoshop to Freelancing
    • Hosted over 300,000 items for sale on our marketplaces from WordPress themes to Stock Photos
    • Showcased over 12,000 items of inspirational design, photography and a host of other creative mediums on Creattica
    • Listed over 8,000 jobs on our freelance job board
    • Reviewed and rounded up over 3,000 apps on our AppStorm network
    • Launched 9 marketplaces, 11 tutorial sites, 9 blogs, 18 books, 7 bundles, 4 Regular Podcasts, and more social media accounts than you can poke a stick at
    • Accumulated close to 1 million RSS subscribers and twitter followers
    • Signed up almost 1 million marketplace members, 90,000 Creattica members, 50,000 FreelanceSwitch members, and 40,000 Tuts+ Premium subscribers
    • Served up well over 1.5 billion pageviews across all our sites since inception

    Holy toledo batman!!

    Thank You

    I can’t say thank you enough to all of you for supporting Envato all these years. Whether you are long-time user of the Marketplaces, Tuts+, AppStorm, FreelanceSwitch or Creattica, or just a casual visitor, we’re really proud that you stop in and use our sites. If you’re one of the thousands of contributors, authors, writers, and subscribers, we’re honored and humbled that you have helped us build this company and filled these sites with such amazing content. And regardless of who you are, we hope that we can continue to provide value and service to you for many more years to come!

    On behalf of the whole team, thank you all!
    Collis
    CEO, Chief Tea Drinker and Web Designer Who Doesn’t Get to Design Anymore
    Envato

    P.S. If you’re not all video’d out, you can check out this video of one of our early Envato staff


  4. James Tyner says:
    September 1, 2011 at 6:49 pm

    In this tutorial, available exclusively to Tuts+ Premium members, you’ll learn to build a card-matching game, in Flash, that uses Flickr as the source of its images. The first part of this two-part series will get you started, leaving you with a basic game structure that you can improve on later.

    Become a Premium member to follow this awesome tutorial, as well as hundreds of other advanced tutorials and screencasts.


    Preview

    Here’s what you’ll create in this part of the tutorial:

    In the second part of the series, you’ll add multiple levels and improve the interface, ending up with this:


    What You’ll Learn

    Naturally, you’ll learn how to search for and retrieve images from Flickr, so that you can use them in other apps and games. But since this tutorial explains how to build a Pairs game from scratch, you’ll also learn about game logic (such as how to detect a match) and interface tweaks (such as the way the cards “flip” over when clicked).


    Active Premium Membership

    Activetuts+ Premium Membership

    We run a Premium membership system which costs $9 a month (or $22 for 3 months!) which periodically gives members access to extra tutorials, like this one! You’ll also get access to Psd Premium, Vector Premium, Audio Premium, Net Premium, Ae Premium, Cg Premium and Photo Premium too. If you’re a Premium member, you can log in and download the tutorial. If you’re not a member, you can of course join today!

    Also, don’t forget to follow @envatoactive on twitter and grab the Activetuts+ RSS Feed to stay up to date with the latest tutorials and articles.


  5. Michael Plank says:
    September 1, 2011 at 7:17 pm

    Flash Professional isn’t the only tool you can use for making Flash apps and games. Earlier in the year we looked at FlashDevelop; now, we’ll take a look at FDT 4, a powerful IDE designed specifically for ActionScript, MXML and haXe development. Read on to find out what it can offer you!

    FDT’s Great Timesaving Features

    The difference between FDT and the Flash Professional code editor or other tools is that it offers tons of timesaving features that let you concentrate on the logic of your code, so you don’t have to bother with syntax problems like a missing closing bracket or a misspelled function call. Like a spell checker, FDT gives you instant feedback about your code and identifies problems before you even compile the project. Before we install and start working with FDT I’d like to give you a taste of some of its most exciting features.

    Code Completion

    The most important feature of FDT, that you will probably use most often, is code completion, also called auto completion. You will never have to type in the whole name of a variable or function again. Simply start writing and hit CTRL + Space to bring up the list of proposals. You can change the auto completion behavior to be triggered on every keystroke (like FlashDevelop does) by going to Preferences > FDT > Editor > Code Assist and turning on “Every Key”.

    Activate auto completion by using the shortcut CTRL + SPACE

    Continue typing to narrow down the list of choices. Use the mouse to select a proposal from the list or use the “Up” and “Down” arrow keys followed by pressing “Return”. You can also use “camel case auto completion” — for example, someMovieClip.gap will offer the function gotoAndPlay().

    Using camel case autocompletion

    Quick Fixes

    My favorite feature of FDT is using its Quick Fix functionality. FDT will not only immediately tell you what is wrong in your code, but also gives you the option to fix it automatically by inserting the missing code. If, for example, you call a function that is not yet available, FDT will add an error marker on the left of that line. The yellow light bulb indicates, that there is a Quick Fix available for this problem. Hit CMD/CTRL + 1 and check out the proposal in the Quick Fix popup:

    Activating Quick Fix using CMD/CTRL + 1

    FDT offers you to create the function sayHello(). Hit “Return” and FDT will automatically insert the function. Use the “Tab” key to cycle through the code statements surrounded by the blue rectangles and change them. Again hit “Return” to finish the Quick Fix procedure.

    After insterting the code cycle through the code statements using Tab

    This feature is not only great for fixing problems with just a few keystrokes, but will also change your coding workflow. You will start forcing problems to make use of a Quick Fix!

    Organize Imports

    Using the shortcut CMD/CTRL + SHIFT + O or choosing Source > Organize Imports from the menu will add all missing import statements at the top of the class. You don’t have to add any imports manually any more. The nicest thing about FDT’s Organize Imports feature is that it will also remove unused imports automatically.

    Choose Organzie Imports from the Source Menu or use the shortcut

    Color Chooser

    I’d like to have a purple label in my Flex app, but what hex color code does purple have? Without having to switch to Flash Pro or Photoshop you can simply use FDT’s color picker to choose a color. Put your cursor over the hex code and activate Quick Fix (CMD/CTRL + 1). Choose “Select color” and use the color picker.

    Use Quick Fix to activate the color chooser

    Code Templates

    As a developer you find yourself typing in recurring code snippets over and over again, like a “for loop” for example. In FDT we can simply use code templates for that. Type in fori, use auto completion (CTRL + SPACE) and select “fori – iterate over array”. This will insert the code snippet for you. Make changes by using the “Tab” key and press “Return” to finish.

    Type in fori and use auto completion to insert a for loop

    To browse through the code templates that are shipped with FDT go to Preferences > FDT Editor > Templates. This is the place where you can also create your own templates! Just take a look at the other templates and you will quickly learn how to create them and use the powerful variables to make them even smarter.

    Refactoring

    FDT has two great refactoring features: Move and Rename. If you want to move a class to another package, you normally need to change the import statements in all classes that use it. Move refactoring in FDT takes care of this automatically. Simply drag and drop the class from one package to another in the Flash Explorer and FDT will take care of the rest.

    Drag and drop classes form one package to another

    If you want to rename a class, function or variable, simply use the Rename refactoring feature (ALT + SHIFT + R). FDT will change the name everywhere in the whole project.

    Use Rename refactoring to rename classes, functions or properties

    Code Navigation Features

    Navigating through your source code is especially important in large projects. Here are some of the most important shortcuts to navigate:

    • F2 – Show Class in Flash Explorer
    • F3 – Open declaration
    • Alt + (CMD) + Left Key – Jump back in History
    • CMD/CTRL + T – Quick Type Hierarchy
    • CMD/CTRL + O – Quick Outline
    • CMD/CTRL + R – Search for References

    The FDT Community

    FDT started out as the first professional ActionScript 2 editor in 2004. There’s a huge and very active community around FDT, that contributes tutorials, blogs about using the new features that are constantly added, helps out on Twitter and posts feature requests and bug reports. The FDT development team gives back this love to the community by listening to their requests and integrating community tools like Joa Ebert’s Apparat or haXe.

    To become part of the FDT community check out the Blog and follow FDT on Twitter or Facebook.


    Installing FDT 4

    Installing FDT is straight forward. Follow these 3 steps to set up your FDT development environment:

    1. Download and install FDT
    2. Download Flex SDKs
    3. Install Debug Flash Player

    To install FDT simply go to http://fdt.powerflasher.com and navigate to the download page. Select one of the installers for Windows, Mac or Linux. If you want to try FDT and don’t have a license yet, fill out the form above to register for a 30 day trial license. After downloading follow the instructions to complete the installation.

    FDT is distributed without any Flex SDK. The Flex SDK is basically a folder that contains compilers, core classes and other tools to compile your Action Script and Flex code to a SWF. You can develop both pure Action Script projects as well as Flex projects using Adobe’s Flex SDK. Go to Adobe Open Source and download the SDKs you want to use in FDT. After downloading and unzipping the SDKs go to FDT > Preferences > Installed SDKs and click the “Add” button to add a Flex SDK.

    In order to debug your Flash applications using FDT’s visual debugger, you need to make sure that the Debug Flash Player is installed on your system. Go to Adobe Flash Player Download:

    • Mac: Download and install Flash Player Plugin content debugger
    • Windows: Download and install Flash Player Active X control content debugger as well as Flash Player Plugin content debugger

    Congratulations, you’ve successfully set up your FDT development environment and can now start coding!


    The FDT Workbench

    FDT after installation
    Click to enlarge
    • Toolbar (top): Find the most important actions like creating new files or compiling your application in the toolbar
    • Flash Explorer (left): This is where you will organize your projects, files and folders
    • Outline (left): A list of properties and functions of the currently opened class
    • Editor (middle): If you open a file, it will be displayed in the editor area
    • Problems (bottom): A list of problems and warnings in your source code

    The panels described above are called “Views” in FDT. You can close views, minimize them or rearrange them by simply dragging a view to a different location. If you would like to reset the views to their default positions go to Window > Reset Perspective. To open additional views go to Window > Show View and select the one you are missing. Views are grouped into so called “Perspectives”.


    Choose Your Workflow

    FDT can be integrated into every Flash/Flex development workflow, whether you want to use FDT in combination with Flash Pro, use FDT without any other tool, or use FDT as a code editor for Flash Pro. This chapter describes those three popular workflows which are most commonly used by Flash developers.

    Workflow 1: FDT Only

    In this workflow we will use FDT as a standalone tool to develop Flash/Flex projects. You don’t even have to have Flash Pro or the Adobe Creative Sweet installed. We will just use FDT to write code and compile it to a SWF.

    Creating a New Project

    Start by right clicking somewhere in the Flash Explorer and select New > New Flash Project. The “Flash Project Wizard” appears.

    Selecting a Project Template

    This wizard let’s you choose from a list of project templates for web, mobile and desktop. We will create a pure Action Script project at this time. Type in the project name “HelloFDT”, select Web > AS3 and click on “Finish”.

    In the Flash Explorer on the left hand side we now see the created project with some files and folders. Double-click the Main.as class in the src folder to open it.

    The created project and the Main class

    FDT stores some project specific settings in the .settings folder and in the .project file. Because you shouldn’t touch those files let’s hide them by clicking on the small down arrow in the top right corner of the Flash Explorer and selecting “Filters”. Now check the “.*” filter and hit “OK”. The .settings folder and the .project file should now be hidden.

    The created project and the Main class

    Testing and Compiling the Project

    Let’s add some lines of code before we compile our project:

    
    
    package
    {
    	import flash.display.Sprite;
    
    	public class Main extends Sprite
    	{
    		public function Main()
    		{
    			graphics.beginFill(0x0000ff);
    			graphics.drawCircle(100, 100, 40);
    			trace("Hello FDT");
    		}
    	}
    }
    

    To compile and debug our simple application, right-click the Main.as class in the Flash Explorer and select Debug As > FDT SWF Application. After the compilation finishes successfully, FDT will launch your application using the “External SWF Viewer”. Take a look at the “Console”; you should also see the “Hello FDT” trace statement there. (If you don’t see it, make sure you have the Debug Flash Player installed.)

    The compiled SWF opened in the External SWF Viewer

    Embedding Assets

    In order to embed an asset like a JPEG image into our SWF we can use the [Embed] Metadata Tag. First of all create a new package named assets in the src folder and drag an image from the Finder/Explorer to the assets package.

    Drag an image to your assets package

    Now we can use the following lines of code to embed the JPEG into our SWF and display it on the stage:

    
    
    package
    {
    	import flash.display.Bitmap;
    	import flash.display.Sprite;
    
    	public class Main extends Sprite
    	{
    		[Embed(source="assets/image.jpeg")]
    		private var ActiveTutsLogo : Class;
    
    		public function Main()
    		{
    			var logo:Bitmap = new ActiveTutsLogo();
        		addChild(logo);
    		}
    	}
    }
    

    We can now use the Debug or Release button in the Toolbar on the top to launch our application. They will always launch the previously launched application. Debugging your application using breakpoints and trace() statements only works if you choose Debug.

    Click Debug or Run to launch your application

    After compilation has finished you should see your SWF with the embedded image. Congratulations!

    Your embedded image

    Workflow 2: FDT with Flash Pro Assets

    This workflow is ideal if you are working together with a designer, who creates graphics and animations in Flash Pro, while you are adding the logic using ActionScript. In this workflow, we will create an animated MovieClip in Flash Pro and control it using ActionScript in FDT. These are the steps:

    • Setup and prepare the project in FDT
    • Create a new FLA file and an animated MovieClip in Flash Pro
    • Export the FLA as SWC library file
    • Instantiate and control the MovieClip using AS3 in FDT

    Setting Up the Project in FDT

    Let’s get started! First of all we will create a new Flash project in FDT. To do so, please follow the exact same instructions as described in Workflow 1: FDT Only > Creating a New Project. As project name I will use “FDTwithFlashPro” this time.

    Creating the FLA and a MovieClip

    In this example I will create a very simple key frame animation with a bouncing ball. Launch Flash Pro and create a new Flash File (ActionScript 3). Select Insert > New Symbol from the menu. Enter the name BouncingBall and check the “Export for ActionScript” check box. If you don’t see the check box, click on the “Advanced” button.

    Creating a new Symbol in Flash Pro

    Don’t forget to check the “Export for ActionScript” check box, otherwise we will not be able to use this asset later on. Next up, I’ll create a simple key frame animation to let the ball bounce. It should look like this. (Basically you can create whatever animation you like in this step; it doesn’t have to be a bouncing ball).

    Creating a bouncing ball animation

    Now it’s time to save the FLA. Go to File > Save As and select the libs folder from the previously created FDT project. Choose Assets.fla as filename and hit “Save”. To use the animated ball MovieClip within our FDT code project, we need to export the Flash Pro Project as a SWC library file. Let’s do this by going to File > Publish Settings and find the “Export SWC” checkbox in the publish dialog. Click “Publish” and Flash Pro will generate the SWC file for you.

    Using the MovieClip in FDT

    Now let’s switch back to FDT. Our project should look like this:

    The FDT project with the assets.swc

    Notice that if you expand the Assets.swc library, you’ll see the BouncingBall MovieClip class included in that library. This is a great feature of FDT, which lets you inspect a SWC library to see which asset classes it contains.

    The final step of this workflow is to instantiate the bouncing ball animation and add it to the stage. Open the Main.as class and insert the following lines of code:

    
    
    package
    {
    	import flash.display.Sprite;
    
    	public class Main extends Sprite
    	{
    		public function Main()
    		{
    			var bouncingBall:BouncingBall = new BouncingBall();
    			bouncingBall.y = 200;
    			addChild(bouncingBall);
    		}
    	}}
    

    That’s it! Hit the “Run” button and you should see the bouncing ball on the stage.

    Final result of the workflow 2 tutorial

    Workflow 3: FDT as Flash Pro’s Code Editor

    The last workflow I want to show you is using FDT as a code editor for a Flash Pro project. You will write code in FDT but compile your project using Flash Pro. FDT has a great feature to automatically switch to Flash Pro and start compilation with just one click. We’ll have a look at this little timesaver as well.

    Setting Up the Project in FDT

    Again, we will start by creating the project in FDT. Simply go to New > New Flash Project and select Web > Flash Professional from the list of project templates. Set the project name to “FDTforFlashPro” and click “Finish”

    Create a new project for Flash Pro

    FDT needs to know the location of your Flash Pro installation. Go to Preferences > FDT > Tools > Flash and set the path to your Flash Pro installation by clicking the “Browse” button. Select your copy of Flash Pro and close the preferences window. Next open the Main.as class and add a trace statement to the constructor like trace("Hello Flash Pro"). Now double click the FDTforFlashPro.fla file from the Flash Explorer to open it. Notice, that the Main class is already set in the Properties panel in Flash Pro. You can click on the pencil button to verify that the class really exists.

    Properties panel in Flash Pro

    The Main class is in place, so we can now launch the project in Flash Pro by selecting Debug > Debug Movie from the menu or by using the shortcut. In the output panel of Flash Pro you should now see the trace output:

    Output panel of Flash Pro showing the trace output

    Great, now we can switch back and forth between FDT and Flash Pro. Write some lines of code in FDT, add classes and logic and switch to Flash Pro to create the assets and debug the project.

    Launching From Within FDT

    To enhance this workflow, there’s a great feature in FDT, which let’s you switch to Flash Pro by just hitting the “Run” button from within FDT to compile and debug the project. In FDT select Run > Run Configurations from the menu.

    Run Configurations Menu

    In the Run Configurations panel double click the “FDT Flash IDE” entry from the menu on the left. This will create a new empty configuration. Now simply set the project and the FLA file using the “Browse” buttons and select TestMovie. That’s it, hitting the “Run” button will switch to Flash Pro and will launch the project! From now on, you can simply hit the “Run” button in the FDT menu bar to launch your project in Flash Pro.

    Run Configuration Settings

    Next Steps

    If you want to learn more about FDT and it’s features visit the FDT Docs page. You will find a great number of tutorials, videos, shortcuts, project templates and a lot more there. Happy coding!


  6. Daniel Branicki says:
    September 1, 2011 at 7:59 pm

    It’s time for another excellent Active Premium tutorial exclusively available to Premium members. At the end of the second part of this series, we had just about got the portals to hide part of the Roly character that was inside them. In this part, we’ll make the portals actually teleport the character.


    Preview

    Let’s take a look at the final result we will be working towards, across the whole of this multi-part tutorial:

    Please view the full post to see the Unity content.

    Hit the number keys 1-8 to try different levels. The aim is to get the little yellow Roly character to the designated end point, using portal mechanics. The demo shows off a few of the different mechanics we’ll introduce.

    Click here to see how far we’ll get by the end of this part.

    Warning: this tutorial is huge! It’s as long as the first and second parts of the series combined.


    Active Premium Membership

    Activetuts+ Premium Membership

    We run a Premium membership system which costs $9 a month (or $22 for 3 months!) which periodically gives members access to extra tutorials, like this one! You’ll also get access to Psd Premium, Vector Premium, Audio Premium, Net Premium, Ae Premium, Cg Premium and Photo Premium too. If you’re a Premium member, you can log in and download the tutorial. If you’re not a member, you can of course join today!

    Also, don’t forget to follow @envatoactive on twitter and grab the Activetuts+ RSS Feed to stay up to date with the latest tutorials and articles.


  7. Eugene Potapenko says:
    September 1, 2011 at 8:06 pm

    In the previous post about Realaxy Editor we spoke about the Traits language, which lets you take advantage of multiple inheritance. Now we turn to another noteworthy opportunity: operator overloading.

    Realaxy ActionScript Editor (RASE) is available here (for Windows, Macintosh OS X, and Linux). Note: if it is your first experience with the editor, please read the RASE how-to.

    Intoduction

    One of the major features added to the RASE beta 10 is operator overloading support, allowing developers to change how the operators (*, +, etc) behave in different circumstances. This feature, as well as multiple inheritance, is an object of a holy war between ardent supporters of two different programming paradigms.

    The advantages of overloading operators are obvious:

    1. Compact style. Your programs might become shorter and more readable; for example, it's much easier to use something like a*b*c than a.multiply(b).multiply(с).
    2. Code often looks more natural. Well defined operator is easier to understand and remember than the name of function a function name. For example, combining two variables of type Point you would prefer to see something like point1 + point2, but not point1.plus(point2).

    The real argument against operator overloading is the losing of the control over your code. It is unclear, sometimes, where an operator is overloaded, and where it is not. Adding an overloaded operator invokes changes in the behavior of existing code that might lead to some unexpected consequences.

    Operator overloading is not included in ActionScript (ECMA3) even though it is proposed for Standard ECMA4. Java does not support operator overloading but both Groovy (“Java with syntactic sugar”) and Scala do. Furthermore, C#'s operators may be overloaded.

    One cannot say whether it is a good or bad thing. However, it is also practically assured that sometimes it is a virtual must-have. For example, when chaining multiple mathematical operations, operator overloading really makes code much more concise, thus improving your understanding of the way it works. But enough theory — let's refer ourselves to practice.

    We talk about a language extension overloadedOperators that was introduced in RASE since Beta 10 (build 8145+).

    An easy way to import it (or any other language) to your project is to press Ctrl+L (Cmd+L) within Realaxy Editor.

    By the way, overloadedOperators in RASE is just a port of the overloadedOperators language from the Jetbrains MPS platform. We just decided not to reinvent the wheel and after investigating the target application domain, came to the conclusion that the Jetbrains solution appears to be sufficient, and meets all our needs. We have added some small bonus features from us.

    We believe, that this is the right way of the Language Oriented Programming that takes the best from other languages and customizes it for own needs. Read more about this later in our forthcoming articles on the creation of language extensions.


    Step 1

    Create a new project with a module inside.


    Step 2

    Call the new root “operators”.


    Step 3

    Add some code for testing to the main class.

    Here we have created two variables, p1 and p2 (type Point). Now we’d like to get a third variable, p3, which would be a result of combining these two points.

    Output these three values: p1, p2, p3. We used expression values from language logging in order to implement the string message for the console output.

    Our code provokes an error message: “Operation can't applied to these operands”. Compiling is impossible.


    Step 4

    Let’s declare the operator overloading. Import com.realaxy.actionScript.overloadedOperators.


    Step 5

    Add a new “OverlodedOperatorsContainer” root: right-click on the package node and choose from a pop-up menu.


    Step 6

    Name it “MyOperators”.

    Here we see two declaration blocks: “overloaded binary operators” and “custom operators declarations”.


    Step 7

    Move to the first block and press Enter. A new operator declaration is added.


    Step 8

    Choose “+” operator. Choose type Point for both sides. Set return value Point (change it from default “void” setting).

    Now we can add a code that would be executed on combining Point with Point (using “+” operator).

    That’s all.

    The red highlight that indicated an error in our class has disappeared.


    Step 9

    Start compiling.


    Step 10

    Create run-configuration for our module.


    Step 11

    Assign the main class (if you had not done it earlier).


    Step 12

    We get the following message on the console:


    Step 13

    Now let’s try to complete a slightly more sophisticated task and re-define operations of subtraction, multiplication, and division. For both Number and Point.

    
    
    operator + (Point, Point) -> Point
    commutative: false
    (left, right)->Point {
      return new Point(left.x + right.x, left.y + right.y);
    }
    
    operator + (Point, Number) -> Point
    commutative: false
    (left, right)->Point {
      return new Point(left.x + right, left.y + right);
    }
    
    operator - (Point, Point) -> Point
    commutative: false
    (left, right)->Point {
      return new Point(left.x - right.x, left.y - right.y);
    }
    
    operator - (Point, Number) -> Point
    commutative: false
    (left, right)->Point {
      return new Point(left.x - right, left.y - right);
    }
    
    operator * (Point, Point) -> Point
    commutative: false
    (left, right)->Point {
      return new Point(left.x * right.x, left.y * right.y);
    }
    
    operator * (Point, Number) -> Point
    commutative: false
    (left, right)->Point {
      return new Point(left.x * right, left.y * right);
    }
    
    operator / (Point, Point) -> Point
    commutative: false
    (left, right)->Point {
      return new Point(left.x / right.x, left.y / right.y);
    }
    
    operator / (Point, Number) -> Point
    commutative: false
    (left, right)->Point {
      return new Point(left.x / right, left.y / right);
    }
    

    Step 14

    Imagine that you need to calculate a point that is located to the left and down by 50 pixels from the center of the distance between the two points.

    This is simple:

    Or even simpler:

    But don’t forget that in a Flasher’s real life it would be like this:

    Compare these figures. It’s good enough reason to use operator overloading in ActionScript projects.


    Step 15

    Now let’s learn how to create our own custom operators.

    First, return to MyOperators declaration and go to custom operators declarations.

    Press Enter to create a new declaration. Visual presentation would be ~=.


    Step 16

    Our custom operator has to check a string for matching a regular expression. To describe such operator’s behavior we add a new overloading, just like we have done it 10 minutes ago with Point. The only difference is adding ~= to autocomplete.

    The left operand must pick up a String, while the right one must be RegExp. Returning value should be Boolean.

    Then add some code that would be executed by our operator, calling test method from the value.


    Step 17

    Create a test operation in Main () to see how it works:

    Fast and easy.

    To avoid confusion in all these custom operators, you should memorise a single keyboard shortcut related with navigation: Ctrl-B (or Ctrl+click on an operator) will lead you to operator’s declaration.

    A good hint: to make a difference between reloaded operator and a built-in one, hover a mouse on it and press Ctrl.

    Of course, if you’re on a Mac, use Cmd instead of Ctrl.


    Step 18

    Let’s extend the behavior of our custom operator with a new feature, commutativity.

    Select the operator and press Alt-Enter. Choose Flip Binary Operation from a pop-up menu. This will swap the two sides, however with an error message, because ~= operator is not yet defined for such operands.

    Proceed to operators declaration. Set commutative = true. The red error highlight should disappear (sometimes you should press F5 to refresh a view).

    In other words, this “commutative” setting is a good old rule that changing the order of summands doesn't change the sum. Now, our ~= operator will still work if we put the RegExp before the String.

    Word of Warning

    OOP gurus warn against overusing this behavior. Sometimes, it involves unexpected effects. Let’s take it on faith and remember it.

    That's all there is to it. We have operator overloading in ActionScript 3.


  8. Activetuts+ Editor says:
    September 1, 2011 at 8:58 pm

    Fans of the Activetuts+ Facebook page can access a new bonus tutorial, this month a prequel (of sorts) to Chong Kah Shiu’s Inverse Kinematics tutorial. Check out the preview here!


    Introduction

    Picturing animation in Vectors is intuitive but understanding Vector mathematics is a pain. In this tutorial, I hope to ease that pain and provide a solution to animation problems using a custom written Vector2D class. We shall look at some fundamental concepts of linear kinematics in the Eulerian approach: displacement, velocity and acceleration. Then, we shall build a simple application with it.


    Final Result Preview

    Let's take a look at the final result we will be working towards. Click on the Flash panel below and control the arrowhead by pressing the four directional keys.


    Download This Fan Bonus Now!

    All you have to do is Like us…


    Not On Facebook?

    Don’t worry, the tutorial will be posted on Activetuts+ in a month’s time!


  9. David Appleyard says:
    September 1, 2011 at 9:53 pm

    If you haven’t heard already, today marks Envato‘s fifth birthday! We celebrated the occasion last week with a 70% commission rate for marketplace authors, and today have announced an exciting birthday bundle. For our wonderful Tuts+ readers, we have prepared a fantastic pack of resources for you to use in your next event or party. Read on to find out how to download them free!


    30 Party & Event Vector Graphics

    First up, we have a pack of vector graphics that should be the perfect accompaniment to your next event. You’ll find cupcakes, balloons, cards, presents, hats, trumpets, and a pair of funky monkeys to get you in the mood to celebrate. Here’s a preview of all the graphics included in the pack:

    Free Party Vector Graphics

    These are included as an Adobe Illustrator file, EPS, and PSD, and have been lovingly designed by our immensely talented Vectortuts+ editor, Sean Hodge!


    The One-Page Event Website

    Sure, you could send out a paper invite to your party, but this is the 21st Century! As a noble Tuts+ reader, it would be far more fitting to produce your very own event website, allowing people to RSVP online. We’re here to help with a fantastic web template that can be used for just this purpose!

    Here’s an example of the site in action, or you can take a look at a live preview here:

    Free Party Vector Graphics

    We’ve used a smattering of the latest web technologies, and made the template incredibly functional:

    • Includes a well-structured PSD
    • CSS3 and HTML5 used throughout
    • AJAX contact form that works out of the box
    • All text is editable, using @font-face from Font Squirrel
    • Looks beautiful in Firefox 3.5+, IE9+, Safari 3.0+ and Chrome
    • Degrades gracefully in older browsers

    The design is crafted and coded by Ian Yates, the editor of Webdesigntuts+, and offered to you completely free!


    Plus… Two Funky Wallpapers

    Would a birthday pack be complete without a couple of accompanying wallpapers? We didn’t think so, and enlisted the services of resident Envato designer extraordinaire, Jacob Zinman-Jeanes to produce two beautiful wallpapers to adorn your desktop. The perfect background for when everyone comes round for the party!

    Free Party Wallpaper
    Free Party Wallpaper

    Download the Freebie Pack!

    As a thank you for being part of our birthday celebration as a Tuts+ reader, we’d love to offer this pack of resources to download completely free:

    Download Now

    While you’re waiting for the download to complete, why not check out the fantastic birthday bundle promotion we’re running at the moment? It’s only available for a limited time!


  10. Daniel Ramirez says:
    September 1, 2011 at 10:50 pm

    In the previous tutorial we had a homing missile chasing after a single target. This tutorial will show you how to convert your homing missiles into heat-seeking missiles for multiple targets.

    If you haven’t read the first Homing Missile tutorial, you may download this .zip file, which contains the source code we’ll be starting with on this tutorial.


    Final Result Preview

    Let’s take a look at the final result we will be working towards:


    Step 1: Modify the Cannon Graphic

    The only Movie Clip in the Library we’ll need to change is the Cannon, since we’ll make it aim at the closest target before shooting. Remember that 0° of rotation means pointing at the right, so make the graphic accordingly.

    Modify the Cannon

    Step 2: Declare Distance Variables for the Cannon

    I’m going to reuse the targetX and targetY variables to calculate the distance of the cannon from the target, so I’ll declare them at the beginning of the class instead of inside the playGame function, as well as a new variable to store the calculated distance:

    
    
    private var missile:Missile = new Missile();
    private var speed:int = 15;
    private var cannon:Cannon = new Cannon();
    private var missileOut:Boolean = false;
    private var ease:int = 10;
    private var target:Target = new Target();
    private var floor:int = 385;
    private var gravity:Number = 0.5;
    private var targetVY:Number = 0;//Current vertical velocity of the target
    private var distance:int;
    private var targetX:int;
    private var targetY:int;
    

    Now the targetX and targetY variables will be already declared for the playGame function:

    
    
    private function playGame(event:Event):void
    {
        if (missileOut)
        {
            if (missile.hitTestObject(target))
            {
                var explosion:Explosion = new Explosion();
                addChild(explosion);
                explosion.x = missile.x;
                explosion.y = missile.y;
                removeChild(missile);
                missileOut = false;
            }
            else
            {
                targetX = target.x - missile.x;
                targetY = target.y - missile.y;
                var rotation:int = Math.atan2(targetY, targetX) * 180 / Math.PI;
                if (Math.abs(rotation - missile.rotation) > 180)
                {
                    if (rotation > 0 && missile.rotation < 0)
                        missile.rotation -= (360 - rotation + missile.rotation) / ease;
                    else if (missile.rotation > 0 && rotation < 0)
                        missile.rotation += (360 - rotation + missile.rotation) / ease;
                }
                else if (rotation < missile.rotation)
                    missile.rotation -= Math.abs(missile.rotation - rotation) / ease;
                else
                    missile.rotation += Math.abs(rotation - missile.rotation) / ease;
    
                var vx:Number = speed * (90 - Math.abs(missile.rotation)) / 90;
                var vy:Number;
                if (missile.rotation < 0)
                    vy = -speed + Math.abs(vx);
                else
                    vy = speed - Math.abs(vx);
    
                missile.x += vx;
                missile.y += vy;
            }
        }
    	targetVY += gravity;
        target.y += targetVY;
        if (target.y > floor)
        {
            target.y = floor;
            targetVY = -18;
        }
    }
    

    Step 3: Make the Cannon Point Towards the Target

    Previously in the playGame function we were only interested in knowing if the missile was out to take care of its rotation and motion. Now we need first to know if the missile hasn’t been shot yet and update the cannon’s rotation.

    
    
    private function playGame(event:Event):void
    {
        if (!missileOut)
        {
            targetX = target.x - cannon.x;
            targetY = target.y - cannon.y;
            cannon.rotation = Math.atan2(targetY, targetX) * 180 / Math.PI;
        }
        else
        {
            if (missile.hitTestObject(target))
            {
                var explosion:Explosion = new Explosion();
                addChild(explosion);
                explosion.x = missile.x;
                explosion.y = missile.y;
                removeChild(missile);
                missileOut = false;
            }
            else
            {
                targetX = target.x - missile.x;
                targetY = target.y - missile.y;
                var rotation:int = Math.atan2(targetY, targetX) * 180 / Math.PI;
                if (Math.abs(rotation - missile.rotation) > 180)
                {
                    if (rotation > 0 && missile.rotation < 0)
                        missile.rotation -= (360 - rotation + missile.rotation) / ease;
                    else if (missile.rotation > 0 && rotation < 0)
                        missile.rotation += (360 - rotation + missile.rotation) / ease;
                }
                else if (rotation < missile.rotation)
                    missile.rotation -= Math.abs(missile.rotation - rotation) / ease;
                else
                    missile.rotation += Math.abs(rotation - missile.rotation) / ease;
    
                var vx:Number = speed * (90 - Math.abs(missile.rotation)) / 90;
                var vy:Number;
                if (missile.rotation < 0)
                    vy = -speed + Math.abs(vx);
                else
                    vy = speed - Math.abs(vx);
    
                missile.x += vx;
                missile.y += vy;
            }
        }
        targetVY += gravity;
        target.y += targetVY;
        if (target.y > floor)
        {
            target.y = floor;
            targetVY = -18;
        }
    }
    

    Now the cannon rotates in relation to the target’s position.


    Step 4: Match the Missile’s Rotation with the Cannon’s.

    The cannon is rotating, but the missile keeps being shot upwards. Replace the hard-coded rotation with the cannon’s current location at the moment the missile is being shot.

    
    
    private function shoot(event:MouseEvent):void
    {
        if (!missileOut)
        {
            addChild(missile);
            swapChildren(missile, cannon);//missile will come out from behind cannon
            missileOut = true;
            missile.x = cannon.x;
            missile.y = cannon.y;
            missile.rotation = cannon.rotation;
        }
    }
    

    Now the missile will look like it’s actually coming out of the cannon.


    Step 5: More than One Target

    Right now the homing missile is program to go after one target, but what if we have more targets? How will it decide which one to go after?

    First, let’s decide how many targets will there be, then we’ll put each target in an Array. In this example I’m going to say there are 2 targets, and I’ll give each target a random position on screen.

    
    
    private var target:Target;
    private var floor:int = 385;
    private var gravity:Number = 0.5;
    private var targetVY:Number = 0;//Current vertical velocity of the target
    private var distance:int;
    private var targetX:int;
    private var targetY:int;
    private var numTargets:int = 2;
    private var targets:Array = [];
    
    public function Main()
    {
        addChild(cannon);
        cannon.x = 50;
        cannon.y = 380;
        addEventListener(Event.ENTER_FRAME, playGame);
        stage.addEventListener(MouseEvent.CLICK, shoot);
        for (var i:int = 0; i < numTargets; i++)
        {
            target = new Target();
            addChild(target);
            target.x = Math.random() * 600;
            target.y = Math.random() * 400;
            targets.push(target);
        }
    }
    

    Now we have more than one target on screen.

    Set the number of targets to appear.

    The missile is still only acknowledging the existence of one target. We’ll fix that next.


    Step 6: Seek the Closest Target

    We have the missile seeking the target variable, so let’s check the targets Array and see which one is closer. The target variable will be referencing the closest at the beginning of the playGame function.

    
    
    private function playGame(event:Event):void
    {
        for (var i:int = 0; i < targets.length; i++)
        {
            targetX = targets[i].x - missile.x;
            targetY = targets[i].y - missile.y;
            var dist:int = Math.sqrt(targetX * targetX + targetY * targetY);//the distance from one point to another in a 2D space.
            if (i == 0 || dist < distance)
            {
                distance = dist;
                target = targets[i];
            }
        }
    

    At this point the closest target is the only one moving, but the missile is acknowledging the existence of both:


    Step 7: Fix the Cannon’s Aim

    You may have noticed that while the missile does seek the expected target, the cannon’s stuck pointing at the same target, regardless if it’s closer or farther than the other one. The distance is set in relation to the missile’s position, so if there’s no missile on stage we need to update its position to match the cannon’s so that it always knows which one is closer.

    
    
    private function playGame(event:Event):void
    {
        for (var i:int = 0; i < targets.length; i++)
        {
            targetX = targets[i].x - missile.x;
            targetY = targets[i].y - missile.y;
            var dist:int = Math.sqrt(targetX * targetX + targetY * targetY);
            if (i == 0 || dist < distance)
            {
                distance = dist;
                target = targets[i];
            }
        }
        if (!missileOut)
        {
            missile.x = cannon.x;
            missile.y = cannon.y;
            targetX = target.x - cannon.x;
            targetY = target.y - cannon.y;
            cannon.rotation = Math.atan2(targetY, targetX) * 180 / Math.PI;
        }
    

    Now the cannon will always aim at the closest target.


    Step 8: Move the Cannon

    Before the missile is shot, the cannon is already pointing to the closest target, and will change direction if moved closer to the other target. Let’s add a couple of lines to position the cannon with the mouse cursor.

    
    
    private function playGame(event:Event):void
    {
        cannon.x = mouseX;
        cannon.y = mouseY;
    

    Now you can move the cannon freely.


    Step 9: Target Hit, Target Destroyed

    To make things more dynamic here, I’m going to relocate a target after being hit by a missile, or replace it by a new one, and leave an Explosion instance in its place.

    
    
    if (missile.hitTestObject(target))
    {
        var explosion:Explosion = new Explosion();
        addChild(explosion);
        explosion.x = missile.x;
        explosion.y = missile.y;
        removeChild(missile);
        missileOut = false;
        explosion= new Explosion();
        addChild(explosion);
        explosion.x = target.x;
        explosion.y = target.y;
        explosion.scaleX = explosion.scaleY = 1.5;
        target.x = Math.random() * 600;
    }
    

    This is what you’ll get:


    Step 10: Multiple Missiles

    We made multiple targets, so now we can make multiple missiles the same way. The difference here is that all missiles must keep moving at all times until they hit, and we’re actually going to remove those which have already exploded, so we need to modify a few lines of our code for this to work. First, we’ll need an Array for the missiles.

    
    
    private var missiles:Array = [];
    

    Then, we need to make sure all the missiles behave properly:

    
    
    private function playGame(event:Event):void
    {
        cannon.x = mouseX;
        cannon.y = mouseY;
        for (var i:int = 0; i < targets.length; i++)
        {
            targetX = targets[i].x - missile.x;
            targetY = targets[i].y - missile.y;
            var dist:int = Math.sqrt(targetX * targetX + targetY * targetY);
            if (i == 0 || dist < distance)
            {
                distance = dist;
                target = targets[i];
            }
        }
        if (!missileOut)
        {
            missile.x = cannon.x;
            missile.y = cannon.y;
            targetX = target.x - cannon.x;
            targetY = target.y - cannon.y;
            cannon.rotation = Math.atan2(targetY, targetX) * 180 / Math.PI;
        }
        else
        {
            for (i = 0; i < missiles.length; i++)//each missile must keep moving
            {
                missile = missiles[i];
                if (missile.hitTestObject(target))
                {
                    var explosion:Explosion = new Explosion();
                    addChild(explosion);
                    explosion.x = missile.x;
                    explosion.y = missile.y;
                    removeChild(missile);
                    missiles.splice(i, 1);//out of the Array
                    if (missiles.length < 1)//only if no missiles are out at all
                        missileOut = false;
                    explosion= new Explosion();
                    addChild(explosion);
                    explosion.x = target.x;
                    explosion.y = target.y;
                    explosion.scaleX = explosion.scaleY = 1.5;
                    target.x = Math.random() * 600;
                }
                else
                {
                    targetX = target.x - missile.x;
                    targetY = target.y - missile.y;
                    var rotation:int = Math.atan2(targetY, targetX) * 180 / Math.PI;
                    if (Math.abs(rotation - missile.rotation) > 180)
                    {
                        if (rotation > 0 && missile.rotation < 0)
                            missile.rotation -= (360 - rotation + missile.rotation) / ease;
                        else if (missile.rotation > 0 && rotation < 0)
                            missile.rotation += (360 - rotation + missile.rotation) / ease;
                    }
                    else if (rotation < missile.rotation)
                        missile.rotation -= Math.abs(missile.rotation - rotation) / ease;
                    else
                        missile.rotation += Math.abs(rotation - missile.rotation) / ease;
    
                    var vx:Number = speed * (90 - Math.abs(missile.rotation)) / 90;
                    var vy:Number;
                    if (missile.rotation < 0)
                        vy = -speed + Math.abs(vx);
                    else
                        vy = speed - Math.abs(vx);
    
                    missile.x += vx;
                    missile.y += vy;
                }
            }
        }
        targetVY += gravity;
        target.y += targetVY;
        if (target.y > floor)
        {
            target.y = floor;
            targetVY = -18;
        }
    }
    
    private function shoot(event:MouseEvent):void
    {
        missile = new Missile();
        missiles.push(missile);//into the Array
        addChild(missile);
        swapChildren(missile, cannon);//missile will come out from behind cannon
        missileOut = true;
        missile.x = cannon.x;
        missile.y = cannon.y;
        missile.rotation = cannon.rotation;
    }
    

    Now when a target is destroyed, the missiles will seek the next target.

    At this point all the missiles are chasing after the same target. In order to make each missile seek its own target, it would be better to make a separate class for the missiles in which you determine the closest target individually.


    Step 11: Make a Crosshair

    At this point you’ve already understood the main idea of this tutorial, but let’s face it, an enemy will not move depending only on its distance to you or your missiles. You can use another indicator, such as a crosshair. Make it a Movie Clip and export it to Actionscript.

    Crosshair Movie Clip.

    Step 12: Use the Crosshair

    Now it will be obvious to anyone which target is being aimed at. Just add an instance of the Crosshair Movie Clip.

    
    
    private var crosshair:Crosshair = new Crosshair();
    
    public function Main()
    {
        addChild(cannon);
        cannon.x = 50;
        cannon.y = 380;
        addEventListener(Event.ENTER_FRAME, playGame);
        stage.addEventListener(MouseEvent.CLICK, shoot);
        for (var i:int = 0; i < numTargets; i++)
        {
            target = new Target();
            addChild(target);
            target.x = Math.random() * 600;
            target.y = Math.random() * 400;
            targets.push(target);
        }
        addChild(crosshair);
    }
    

    Then place it on the target‘s position as the last instruction in the playGame function.

    
    
    	targetVY += gravity;
        target.y += targetVY;
        if (target.y > floor)
        {
            target.y = floor;
            targetVY = -18;
        }
        crosshair.x = target.x;
        crosshair.y = target.y;
    }
    

    You’ll get a crosshair marking the closest target’s position.

    The closest target is marked by the crosshair.

    Step 13: Move All Targets

    Remember what I said about the missiles? The same applies to the targets: They’ll look better in their own class with a set of instructions of its own. This is just a quick example, but in your game I don’t recommend coding all the objects in the Main class. The more complex your game is, the less stuff you’ll code inside the Main class.

    The targets are already in an Array, which is already being checked in a for loop, so I’ll move the bouncing instructions inside the for loop, so that all the targets, no matter how many, will move the same at all times.

    
    
    private function playGame(event:Event):void
    {
        cannon.x = mouseX;
        cannon.y = mouseY;
        targetVY += gravity;
        for (var i:int = 0; i < targets.length; i++)
        {
            targetX = targets[i].x - missile.x;
            targetY = targets[i].y - missile.y;
            var dist:int = Math.sqrt(targetX * targetX + targetY * targetY);
            if (i == 0 || dist < distance)
            {
                distance = dist;
                target = targets[i];
            }
            targets[i].y += targetVY;
            if (targets[i].y > floor)
                targets[i].y = floor;
        }
        if (target.y >= floor)
            targetVY = -18;
        if (!missileOut)
        {
            missile.x = cannon.x;
            missile.y = cannon.y;
            targetX = target.x - cannon.x;
            targetY = target.y - cannon.y;
            cannon.rotation = Math.atan2(targetY, targetX) * 180 / Math.PI;
        }
        else
        {
            for (i = 0; i < missiles.length; i++)
            {
                missile = missiles[i];
                if (missile.hitTestObject(target))
                {
                    var explosion:Explosion = new Explosion();
                    addChild(explosion);
                    explosion.x = missile.x;
                    explosion.y = missile.y;
                    removeChild(missile);
                    missiles.splice(i, 1);
                    if (missiles.length < 1)
                        missileOut = false;
                    explosion= new Explosion();
                    addChild(explosion);
                    explosion.x = target.x;
                    explosion.y = target.y;
                    explosion.scaleX = explosion.scaleY = 1.5;
                    target.x = Math.random() * 600;
                }
                else
                {
                    targetX = target.x - missile.x;
                    targetY = target.y - missile.y;
                    var rotation:int = Math.atan2(targetY, targetX) * 180 / Math.PI;
                    if (Math.abs(rotation - missile.rotation) > 180)
                    {
                        if (rotation > 0 && missile.rotation < 0)
                            missile.rotation -= (360 - rotation + missile.rotation) / ease;
                        else if (missile.rotation > 0 && rotation < 0)
                            missile.rotation += (360 - rotation + missile.rotation) / ease;
                    }
                    else if (rotation < missile.rotation)
                        missile.rotation -= Math.abs(missile.rotation - rotation) / ease;
                    else
                        missile.rotation += Math.abs(rotation - missile.rotation) / ease;
    
                    var vx:Number = speed * (90 - Math.abs(missile.rotation)) / 90;
                    var vy:Number;
                    if (missile.rotation < 0)
                        vy = -speed + Math.abs(vx);
                    else
                        vy = speed - Math.abs(vx);
    
                    missile.x += vx;
                    missile.y += vy;
                }
            }
        }
        crosshair.x = target.x;
        crosshair.y = target.y;
    }
    

    Take a look:


    Conclusion

    Homing missiles, heat-seeking missiles, both are a fun and useful weapon to have around in a shooting game or maybe some other type of app. This tutorial shows an example of its use and the algorithm to make it, but for best practices it is recommended that you have separate classes for the missiles and the targets, unless your app is as simple and short as this one.

    I hope you’ve found this tutorial useful. Thanks for reading!


Leave a Reply

Click here to cancel reply.

search search search search search
Find an Article
Categories
  • Flash Video Training
  • Hints and Tips
  • Recommended
Please Support Our Sponsors
Recent Posts
  • Workshop Coding Challenge: Fix This Breakout Game
  • Enable the Latest AIR SDK in Flash Professional CS5.5+
  • Quick Tip: Versioning Your Files With Dropbox (via Webdesigntuts+)
  • Workshop: Nuclear Outrun – Critique
  • Understanding Variables, Arrays, Loops, and Null: The Post-it Note Analogy
Tag Cloud
2011 ActionScript Active Activetuts+ Adobe animation Basic Basix Best Build Button Character Create Creating Critique Custom design Effect Effects Files Flash from Game Guide HTML5 Introduction Macromedia Motion Muzzle part Player Premium Professional Quick Silverlight Simple Text Tool Tutorial Tuts+ Tween Using Video website Workshop
About Our Site:

Hey there and welcome to "Flash Video Training Source", a resource for anybody interested in learning more about Adobe's great tool. We feature educational videos, which will help you master Adobe Flash and help you get to know all of its features. We at "Flash Video Training Source" believe that video training and video... more

Why don't you follow us on Twitter and get the latest video tutorials twitted to your account. Just click on the floating twitter bar to your right!

Go Back In Time
May 2012
M T W T F S S
« Apr    
 123456
78910111213
14151617181920
21222324252627
28293031  
Pretty Blank Box
top

Blogroll

  • Development Blog
  • Documentation
  • Plugins
  • Suggest Ideas
  • Support Forum
  • Themes
  • WordPress Planet

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Archives

  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
Powered by WordPress  |  Designed by Elegant Themes  |  Lightning Fast Hosting by Site 5 Hosting