logo
468x60-2-495


  • Home
  • Privacy Policy
  • About
search
top
Jan 3, 2012 Posted on Jan 3, 2012 in Hints and Tips | 10 comments

Free Greensock-Based Flash Slideshow Framework (With Premium Source Files)

Something a little different for you this week: a Flash slideshow framework. As well as finding it directly useful for any presentations you may give, Premium members can download the full source code, and take it apart to see how the Greensock tweening libraries were used to put it together.


Preview

There are three example slideshows created with the framework:



A simple image rotator (with keyboard control).


A grid slideshow (also with keyboard control).


A spread slideshow (the slides scale and rotate to come into focus).

The slideshows support images, SWFs, and FLV videos, and are all defined by a single simple XML file.


Download

All the files you need to actually use the slideshows are available in this free ZIP file.

If you’re a Premium member, you can download the source files as well; these use Greensock’s LoaderMax and TweenLite libraries, so make excellent examples. You could use these files as examples of how to use those libraries, or could extend them to add your own flair or new features.


Active Premium Membership

We run a Premium membership system 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, Photo Premium, and Mobile Premium. 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!



View full post on Activetuts+

banner ad

10 Responses to “Free Greensock-Based Flash Slideshow Framework (With Premium Source Files)”

  1. Kirit Tanna says:
    January 3, 2012 at 11:31 am

    Something a little different for you this week: a Flash slideshow framework. As well as finding it directly useful for any presentations you may give, Premium members can download the full source code, and take it apart to see how the Greensock tweening libraries were used to put it together.


    Preview

    There are three example slideshows created with the framework:



    A simple image rotator (with keyboard control).


    A grid slideshow (also with keyboard control).


    A spread slideshow (the slides scale and rotate to come into focus).

    The slideshows support images, SWFs, and FLV videos, and are all defined by a single simple XML file.


    Download

    All the files you need to actually use the slideshows are available in this free ZIP file.

    If you’re a Premium member, you can download the source files as well; these use Greensock’s LoaderMax and TweenLite libraries, so make excellent examples. You could use these files as examples of how to use those libraries, or could extend them to add your own flair or new features.


    Active Premium Membership

    We run a Premium membership system 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, Photo Premium, and Mobile Premium. 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!


  2. David Appleyard says:
    January 3, 2012 at 12:17 pm

    Each month, we bring together a selection of the best tutorials and articles from across the whole Tuts+ network. Whether you’d like to read the top posts from your favourite site, or would like to start learning something completely new, this is the best place to start!


    Psdtuts+ — Photoshop Tutorials

    • Create a Festive Cocktail Using Photoshop’s 3D Capabilities

      Create a Festive Cocktail Using Photoshop’s 3D Capabilities

      For many of our readers, this time of year is filled with family, friends, and celebration. In this tutorial, we will explain how to create a festive cocktail using Photoshop’s 3D capabilities just in time for your New Year’s celebrations. Let’s get started!

      Visit Article

    • Create a Dark, Conceptual Photo Manipulation With Stock Photography

      Create a Dark, Conceptual Photo Manipulation With Stock Photography

      In this tutorial we will be teaching how to integrate elements from different sources to create a realistic photo manipulation with dark and conceptual elements. You will learn some lighting and blending techniques as well as some interesting post-production tips. Let’s get started!

      Visit Article

    • Create High-End Action Figure Packaging – Tuts +  Premium Tutorial

      Create High-End Action Figure Packaging – Tuts + Premium Tutorial

      With collectables, the packaging of the product is often as important as the craftsmanship of the product itself. In this two-part Tuts+ Premium tutorial, author Tim Kyde will explain how to create packaging for a high-end 1/6 scale action figure. Part 1 of this tutorial will explain how to shoot your own photography and create a print-ready outer sleeve and inner packaging for our action figure. This tutorial is available exclusively to Tuts+ Premium Members — Join Now to get started!

      Visit Article


    • Nettuts+ — Web Development Tutorials

    • Wrangling with the Facebook Graph API

      Wrangling with the Facebook Graph API

      Have you ever wanted to learn how to make your applications more social with Facebook? It’s much easier than you think!

      Visit Article

    • From Idea to Market: How We Built Gradient

      From Idea to Market: How We Built Gradient

      Retracing the steps you’ve taken is a helpful way to understand how well you’ve executed your vision – whatever that might be. What could you have done better? What should have been avoided? Today, I’ll share what we’ve learned (and are still learning) while crafting Gradient. It’s an experience that has changed everything for us.

      Visit Article

    • Should You Learn CoffeeScript?

      Should You Learn CoffeeScript?

      I’d imagine that I represent a large portion of the web development community. I’m very intrigued by CoffeeScript; I’ve even learned the syntax and used it in a few demos. However, I haven’t yet taken the plunge and used it in a real project. It comes down to this one question for me: is CoffeeScript something that is truly worth investing time and effort into learning?

      Visit Article


    • Vectortuts+ — Illustrator Tutorials

    • 75 Outstanding Tutorials, Quick Tips, Articles and Interviews from Vectortuts+ in 2011

      Outstanding Tutorials, Quick Tips, Articles and Interviews from Vectortuts+ in 2011

      As the year comes to an end and we pack up our vector tools for some well deserved rest and relaxation, let’s take a look back at some of the best and most inspiring Vectortuts+ articles and tutorials for 2011.

      Visit Article

    • Community Project: 2012 Calendar Design Project

      Community Project: 2012 Calendar Design Project

      Vectortuts+ loves Illustration and discovering new talent, so today we are proud to be launching a new community project that combines both, the Vectortuts+ 2012 Calendar Design Project. The best thing is, you can be a part of it! Find out how to get involved, at the jump.

      Visit Article

    • Quick Tip: How to Create a Watercolor Background Using Adobe Illustrator

      Quick Tip: How to Create a Watercolor Background Using Adobe Illustrator

      In this tutorial we will learn how to create Watercolor Background using a Gradient Mesh, tools of deformation and Blending Modes. The techniques which are described here allow the creation of complex textural backgrounds in a simple and effective way.

      Visit Article


    • Webdesigntuts+ — Web Design Tutorials

    • A Year in Web Design: How the Experts Saw 2011

      A Year in Web Design: How the Experts Saw 2011

      “What did you find most memorable about the world of web design in 2011?” That’s the question I posed to some of our industry’s shining stars last week. One word cropped up more than any other (can you guess?) and everyone had plenty to say. See for yourself after the jump, and let us know what rocked your boat in 2011!

      Visit Article

    • Get Into LESS: the Programmable Stylesheet Language

      Get Into LESS: the Programmable Stylesheet Language

      I don’t like CSS. Plain and simple. It makes the World go round on the web, yet the language is restrictive and hard to manage. It’s time to spruce up the language and make it more helpful by using dynamic CSS with the help of LESS.

      Visit Article

    • Say Hello to the HTML Email Boilerplate

      Say Hello to the HTML Email Boilerplate

      Figuring out html email will test the patience of any human being. A seemingly small formatting issue will inevitably arise and you think to yourself, “self, I’m a world class web developer type person schooled in the latest and greatest html5/css3/whatever, I can tackle this with plenty o’ keystrokes to spare.”

      Visit Article


    • Phototuts+ — Photography Tutorials

    • 10 Tips to Get Started with Still Life Photography

      Tips to Get Started with Still Life Photography

      There arent many photographic practices that date back further than still life photography. When photography originated, it was necessary for exposures to be quite long, so photographing static objects was the ideal subject matter. However, as the technology developed, the fascination for capturing still life has remained and is still one of the most viable photographic professions today.

      Visit Article

    • Is It Worth It? Some Gear Buying Advice

      Is It Worth It? Some Gear Buying Advice

      A lot people believe their photography will improve “if only…” With the holidays approaching, a lot of avid wanna-be photographers, amateurs, and professionals will be making wish lists for gear that they erroneously believe will make them better photographers. There are many forums, YouTube videos, and articles pandering how camera/lens/light/brand/voodoo doll will make your photos better. Today, we’ll examine that idea.

      Visit Article

    • 50 Superb Photos of Paths and Stairways

      Superb Photos of Paths and Stairways

      “Follow the Yellow Brick Road,” an infamous movie quote inspired by a pathway to a land of dreams. Wherever your paths take you and whatever amount of stairs you have to climb, its always worth it to see whats at the end, but more importantly to enjoy the journey. Today’s collection gathers dozens of images of paths and stairways, images that symbolize something different to every person.

      Visit Article


    • Cgtuts+ — Computer Graphics Tutorials

    • Freebie: Epic 3D Character Model Of Pyro From Team Fortress 2

      Freebie: Epic 3D Character Model Of Pyro From Team Fortress 2

      Today we’re super excited to bring you this amazingly detailed character model from Cgtuts+ regular Shaun Keenan. Shaun has re-created “Pyro” from Valve’s hit game Team Fortress 2 in glorious detail, and is making the model available to the Cgtuts+ community for free!

      Visit Article

    • Digital Matte Painting And Projection Basics: From Photoshop To Maya To Nuke, Part 1 – Tuts+ Premium

      Digital Matte Painting And Projection Basics: From Photoshop To Maya To Nuke, Part 1 – Tuts+ Premium

      This Tuts+ Premium tutorial series covers a variety of basic techniques for both creating and projecting matte paintings using Photoshop, Maya and Nuke. The first part of the tutorial will cover how to approach the creation of a matte painting, the research and background knowledge you need, the concept, and finally starting to create your matte painting in Photoshop. Log in or Join Now to get started!

      Visit Article

    • Create A Flying Paper Animation In 3D Studio Max With Thinking Particles

      Create A Flying Paper Animation In 3D Studio Max With Thinking Particles

      In this tutorial by Cristian Pop, you’ll learn how to create a nice flying papers effect in 3d Studio Max using the power of Thinking Particles. We’ll start by creating the paper shapes and materials, then move into Thinking Particles to set up the rules and look at how we can combine them to create the flying paper effect.

      Visit Article


    • Aetuts+ — After Effects Tutorials

    • How To Track Footage That Is Out Of Focus

      How To Track Footage That Is Out Of Focus

      In this tutorial we are going to take a look at a simple, but interesting idea. The main point will be to show you how to work with footage that is out of focus making if difficult to track. After we track it we are going to attach the camera interface elements and fake some depth of field to create the illusion that they are floating in space and shift in and out of focus like the rest of the scene.

      Visit Article

    • DIY – Create A Camera Dolly Completely From Scratch

      DIY – Create A Camera Dolly Completely From Scratch

      Ever wonder how to get smooth footage from your video camera? Today you will learn how to build a Camera Dolly that will help you acquire this type of footage. Get out those dusty power tools, buy some cheap supplies at your local hardware store, and you’ll be on your way to capturing some amazing footage in no time!.

      Visit Article

    • How To Create A Dr. Who Time And Space Vortex – Tutsplus Premium

      How To Create A Dr. Who Time And Space Vortex – Tutsplus Premium

      In this tutorial well be creating a Time & Space Vortex (like that used in Doctor Who) completely inside of After Effects. We will be using Trapcode Particular and Trapcode Shine to create the vortex. I will then teach a vital Expression that drives the camera and completes the Effect. Once you have mastered the effect, you can personalize it to create whatever Time-Tunnel you desire! All of Time and Space awaits you…

      Visit Article


    • Audiotuts+ — Audio & Production Tutorials

    • Drum Compression: Get Your Attack and Release Times Correct

      Drum Compression: Get Your Attack and Release Times Correct

      Compression can be a tricky one to get your head around, and even if you’ve got your head around the threshold and ratio settings without the attack and release times being set correctly it will always be difficult to get the desired effect. This quick tip will outline a really handy trick I learned from a friend a few years ago which allows you to get your attack and release times just right. It’s primarily designed to work on drums but the same principles will apply to any percussive sound.

      Visit Article

    • Quick Tip: Punchier Drums with the New York Compression Trick

      Quick Tip: Punchier Drums with the New York Compression Trick

      Ever have a mix where you wish the drums were bigger, more energetic, more in-your-face? I first heard about this technique in Bobby Owinksis, The Mixing Engineers Handbook, and it has since become a staple in my bag of tricks. The technique is a more aggressive take on parallel compression that can really add punch to your mix.

      Visit Article

    • 3D Mixing Part 6: Depth

      D Mixing Part 6: Depth

      In this segment of our mix down tutorial, we are going to begin to look in depth into depth. Depth within any mix and listening situation is paramount to proper sonic understanding. Much like we see in 3D, we hear in 3D and taking out any one of these dimensions only serves to create a flat and unnatural sound. As such, the most common tools which give the illusion of depth (reverb and delay) become an important and necessary part of mixing.

      Visit Article


    • Activetuts+ — Flash, Flex & ActionScript Tutorials

    • Getting Started With EaselJS: A Flash-Like Interface for the HTML5 Canvas

      Getting Started With EaselJS: A Flash-Like Interface for the HTML5 Canvas

      There’s been some resistance from Flash developers to our new HTML5 content. In this article – aimed at experienced AS3 coders – we’ll look at EaselJS, a JavaScript library that makes working with the HTML5 canvas very similar to working with the Flash display list.

      Visit Article

    • AS3 Quick Tip: Hacking the Event Flow

      AS3 Quick Tip: Hacking the Event Flow

      Sometimes you may find yourself needing to modify the behavior of a component for a user input event. This article will explain how to do so by modifying the event object in-flight, before it’s processed by the component. That’s right, you can lie and cheat. In code.

      Visit Article

    • 2011 in Flash and Web Apps: A Retrospective

      in Flash and Web Apps: A Retrospective

      With the year 2011 at a close, it is time to reflect upon some of the major industry events of the year. A lot happened… we’ll pick out some of the bits and pieces that will be most interesting to browser app and game developers from the world of industry, web, runtimes, operating systems, mobile, and more!

      Visit Article


    • Wptuts+ — WordPress Tutorials

    • WordPress 3.3 “Sonny” Is Finally Here! What’s New?

      WordPress 3.3 “Sonny” Is Finally Here! What’s New?

      The latest and greatest version of the WordPress software — 3.3, named ’Sonny” in honor of the great jazz saxophonist Sonny Stitt — is immediately available for download or update inside your WordPress dashboard. We’ll be covering lots of the new features of 3.3 this week, but for now, go and great the latest version! As we’ve mentioned before, it’s the best way to keep your WordPress site safe and stable.

      Visit Article

    • Getting Loopy – Ajax Powered Loops with jQuery and WordPress

      Getting Loopy – Ajax Powered Loops with jQuery and WordPress

      In this tutorial, we give you a starting point for creating AJAX interaction in your blog. We follow a step by step process, showing you how to load posts based on the viewers page scroll. The tutorial covers enqueueing scripts, setting up an AJAX handler, how to get a file outside of WordPress to use WordPress functions and access the database, and logic for loading posts on user page scroll.

      Visit Article

    • 5 “Saintly” Practices that All WordPress Developers Should Strive For

      Saintly” Practices that All WordPress Developers Should Strive For

      Here on Wptuts+, we talk a lot about the ‘how’ and less about the ‘why.’ Of course, we are a tutorial site, so that’s the goal, right? Well, as a followup to last month’s article on the “Cardinal Sins of WordPress Plugin Development“, today we’re going to look at a few practices that, if every developer followed, would make the world a better place (well, at least our world!).

      Visit Article


    • Mobiletuts+ — Mobile Development Tutorials

    • Getting Started With Kindle Fire Development

      Getting Started With Kindle Fire Development

      The Kindle Fire is the new touchscreen and e-book reader from Amazon. This device has generated a lot of buzz, and for good reason! It is currently the best selling Android tablet, with millions of units already sold. This tutorial will teach you how to begin making apps with the Android SDK specifically targeted for the Kindle Fire.

      Visit Article

    • iOS 5 SDK: Storyboards

      iOS 5 SDK: Storyboards

      Storyboarding is one of the most exciting new features about the iOS 5 SDK. Take a look at the wealth of functionality offered by Storyboards in today’s iOS 5 SDK tutorial!

      Visit Article

    • Titanium Mobile: Build an Image Uploader

      Titanium Mobile: Build an Image Uploader

      This tutorial will demonstrate how to build a custom progress bar by creating an image uploader with Titanium Mobile. Specifically, the demo project will allow you to select an image from the device photo gallery and upload it to a remote server for storage. Both the Titanium Mobile code and the server-side code will be explained. Now, let’s get started!

      Visit Article


    Happy New Year!

    We’d like to wish all our readers a very Happy New Year! Why not take a look at our Holiday Wishes post to see a video message from the Envato HQ team, and find out more about what you might have missed over the Christmas period.

    We hope you’ve enjoyed everything that we’ve had to share this year, and look forward to publishing thousands more top-quality tutorials, articles, freebies, and resources in 2012.

    Thanks for being part of the Tuts+ community!


  3. Joseph Labrecque says:
    January 3, 2012 at 12:58 pm

    With the year 2011 at a close, it is time to reflect upon some of the major industry events of the year. A lot happened… we’ll pick out some of the bits and pieces that will be most interesting to browser app and game developers from the world of industry, web, runtimes, operating systems, mobile, and more!


    Early in the Year…

    In the first part of this year, we saw the release of Android 3.0 “Honeycomb” – a tablet-specific version of the popular mobile operating system. One of the items that this version of the OS was faulted for was its initial lack of Flash Player support. This would later be remedied, but not before a lot of negativity was expressed over the omission. Now that the year is almost at its end, we have a greater understanding of what may have contributed to this delay… and it is a sad reminder that even for large enterprises, resources are far from limitless.

    The year was still relatively young when March brought us more interesting developments. Adobe released a project on Labs, code-named “Wallaby”, an AIR application that converts specific FLA files to HTML-based output to perform animations in the browser when Flash is not supported (iOS/WP7), or when HTML output is desired. With Adobe now talking about HTML output directly from Flash Professional, one wonders whether that may be the end result of this prototype? The same month also brought us AIR 2.6 and Flash Player 10.2 for Android, which finally provided Honeycomb tablets with mobile Flash Player.

    At this same time, Unity came out with a huge surprise announcement: future versions of the platform tools would be able to compile to SWF in order to support Stage3D in the Flash Player. This announcement opened up a whole lot of existing 3D tooling for Flash developers (especially since Adobe basically has no 3D tooling support for games), and a wider distribution market for current Unity developers as well. Both camps benefit! This was also a clear demonstration of Adobe’s initial strategy around Stage3D: allowing tooling providers and framework engineers to build higher-level components around the core Stage3D APIs.

    We also saw an interesting move from Microsoft during this time, with a public effort by the company to convince users of IE6 to upgrade their browser through the ie6countdown.com website. When even Microsoft is running a campaign to get users to upgrade from IE6… well… need I say any more? The website is actually an informative little resource that tracks the decline of the much-despised browser. Here’s looking forward to 0%!


    Springtime Advances…

    A number of major announcements from Adobe occurred in the Spring, and seemed to center around the 360|Flex conference in Denver. First, Adobe announced Creative Suite 5.5 and an entirely revised release schedule: instead of a new version of the Creative Suite every 18 months, Adobe would be releasing a new version every year to keep tooling relevant in light of the rapid changes taking place on the web and through mobile devices. The announcement was followed a few weeks later by the availability of CS5.5 alongside major updates to Flash Builder, Flash Professional, and the Flex framework.

    During 360|Flex, the Adobe Flex team took the stage to make another important announcement: the founding of a new relationship between Adobe and the community in the form of the Spoon project. While Flex had actually been an open source framework for years at this point, there was no organized way in which the community could actually contribute patches and changes in an acceptable fashion. The Spoon project would establish a modified fork (or spoon [oh, now I get it - Ed]) of the codebase that would be community driven. Patches from this fork would then be accepted and integrated into Adobe’s version of Flex as need be. Now that we sit at the close of this year, we can see how vitally important this announcement was to the current situation…

    In other Adobe news, Flash Player 10.3 was released and Adobe demonstrated Flash Media Server 4.5 and the implementation of HTTP Live Streaming (HLS) – a form of streaming technology that chunks data into tiny packets for transport over the normal HTTP protocol while also allowing multi-bitrate support for varying devices and connection speeds. This enables FMS to stream video to iOS using the HTML <video> tag. Cool.

    One of the bigger announcements that came out of the Google I/O conference this year was the Google Chromebook. The Chromebook is a netbook-class device that is meant to run only browser-based applications, resulting in super-fast startup times and persistent storage in the cloud. Google also announced a new update to Google TV built on Honeycomb. With this, not only would every user get the benefits of an updated Android OS, but the Android Market would be enabled on Google TV devices, allowing developers to target these systems alongside smartphones and tablets. (The lack of Market access on the original Google TV was a huge oversight, in the opinion of many developers.)

    One last notable item for Spring was the release of the BlackBerry Playbook. This was a long time coming and provided customers looking for a powerful tablet device an alternative to iOS and Android, since the Blackberry Tablet OS is built upon QNX – known for its stability and overall reliability. Unfortunately, the tablet hasn’t really taken off since the device still doesn’t have a native email client, calendar, or Angry Birds*.

    *Yes, I am kidding about Angry Birds. Mostly.


    Summer…

    A lot happened over the summer months. Flash Builder 4.5.1 was released by Adobe, adding full Flex mobile support for Android, iOS and Playbook. Prior to this, developers needed to use all sorts of tricks to compile applications for all these devices; with 4.5.1, it could all be done through the application GUI. At the same time, Adobe also released AIR 2.7 and mysteriously dropped support for AIR on Linux Desktop with the allowance that Open Screen Partner members may adopt the responsibility to get future versions of the AIR runtime on Linux distributions… although, at the time of writing, nothing has yet come of this. (What’s going on, Adobe?)

    In Apple’s world, Mac OSX 10.7 Lion was released – marking what may be the first signs of iOS influence within the desktop operating system with an integrated app store and advanced gesture support. Many were taken aback by the integration of mobile-like elements and concepts into a desktop OS… but since then, Windows appears to be taking a similar path, so this is probably not going to be an isolated idea.

    Google took a cue from Adobe’s “Wallaby” project and released their own Flash to HTML conversion tool called Swiffy. This tool differed from “Wallaby” in that it converted SWF files instead of FLA files, and used an entirely different output. Still, the spirit and limitations of both tools are shared: convert old Flash-based content (AS2, limited capability graphics) to something that can be read natively through web browsers.

    In July Sony made news due to their joining the Open Screen Project, as well as their release of some interesting Android-based tablets. They also announced the “Adobe AIR App Challenge” to get developers interested in targeting their tablets using AIR 3 betas along with ActionScript Native Extensions (ANE) which targeted specific features of their hardware. With Adobe’s recent new focus on gaming, this was an attractive contest for developers to participate in and it gave users exposure to new possibilities with ANEs in AIR 3.

    In strange tablet news, the HP TouchPad with WebOS was released – and then discontinued merely weeks later. This was notable for Flash developers since it was long expected that Adobe was working closely with Palm and then HP to get mobile Flash Player on PalmOS/WebOS devices. Obviously this was never to be. Since that time, users have been able to get Android running on the system, giving the tablet a certain post-mortem desirability.

    Anyone who was at Adobe MAX last year will remember a prototype that was shown during the Sneaks called “Project EDGE” – which demonstrated an animation platform targeting HTML5, JavaScript, and CSS3. Adobe Edge Preview 1 was made available for download on Adobe Labs over the Summer and received a rather impressive number of downloads over the first week. While Edge Preview 1 was limited in functionality, it showed great promise.

    Around the same time that Edge first saw the light of day, Adobe also launched a new beta resource website, called The Expressive Web. This is a project which Adobe has put together with the goal of creating both a resource and a showcase for some of the most creative and expressive features being added to the web. In addition to highlighting and providing information on 12 new HTML5 and CSS3 features, the site itself makes extensive use of new features such as CSS3 Transitions, CSS3 Transform, Web Storage and more to provide a visually compelling resource for learning about HTML5 and CSS3.

    Summer also marked the end of the Adobe AIR Marketplace. The service existed for three years and was a good distribution channel for AIR applications at the time. Since then, a number of other markets have emerged on both mobile and desktop, making Adobe’s offering a bit redundant. One of the most unfortunate things about this closure is that a lot of people had links to the AIR Marketplace for app downloads… these all went dead on August 31st.


    Autumn…

    A few weeks before Adobe MAX, Microsoft held their BUILD conference at which they released a developer preview of Windows 8. This was the first hands-on of the new Metro interface borrowed from Windows Phone 7, and it was given mixed reviews by the press. The most startling revelation about Metro, though, was that Internet Explorer 10 running in Metro would have no support for browser plugins. Zero. No Flash Player, no Silverlight, no Java… nothing but HTML, CSS, and JavaScript. If a user wants to use any of these plugins, they must exit out of the Metro interface to bring up the “classic” version of IE10 within which plugins like Flash Player would function just as normal.

    So now we have two major players in mobile – Apple and Microsoft – saying “no” to mobile Flash Player in favor of a pure HTML experience. (Unfortunately, this goes against the HTML5 spec, since the spec actually now allows <embed> as a valid element!) Even more shocking were the increased rumors that Microsoft may be scaling back hard on Sliverlight moving forward. A rough time for Silverlight developers, indeed.

    October brought us Adobe MAX, at which Adobe revealed their new cloud platform, the Creative Cloud, and also a series of touch apps for tablets that aim to bring creative expression to tablet devices. While tablets are commonly seen more as consumer tools, Adobe wants to change that perspective and these tablet applications go some way toward that goal. The Creative Cloud also includes a subscription service to the Creative Suite for about $50 a license. Not too bad – but not everyone wants to be bound to a subscription model. We’ll see what the details are once this is all finalized next year.

    There were also a number of new releases timed around Adobe MAX, including Flash Player 11, AIR 3, and Edge Preview 3. The Flash Runtimes included many great new features, among which is Stage3D (formerly Molehill) which allows full GPU-accelerated 3D rendering in the browser. In fact, during the Day 2 keynote, Adobe was able to show off the full Unreal engine (ported to AS3 using Alchemy) running in Flash Player 11. Pretty spectacular. It is also worth noting that practically all of the new touch apps were built with AIR 3.

    Even with all of the great announcements for Flash developers, many who left MAX did so with a sense of foreboding… Adobe seemed to be talking up HTML a lot more than Flash – and if you didn’t go to any of the Flex futures sessions, you probably came away with a rather empty feeling. This would play out in the weeks ahead as Adobe made some rather dramatic decisions around the future of the platform.


    Winter Falls… Hard

    On November 9th, Adobe was scheduled to have its regular analyst meeting to talk about how things were going for the company and lay some groundwork for the direction of the year ahead. Also, as has become custom, everyone expected there to be a bit of restructuring and associated layoffs around the same time. What actually happened is something the industry is still reeling from.

    Reports began spreading the evening before that Adobe was set to announce the end of the mobile Flash Player. There were also rumors that the entire Flash Professional team was laid off. Now, rumors are often just that and do not ever actually see the light of day. Many in the community thought that with Adobe being so strong on mobile Flash Player with so many successes that this had to be just another ugly rumor and could not possibly be true.

    Unfortunately, this time, the rumor was 100% accurate. A press release and blog post the next morning confirmed that Adobe did intend to drop all future work on mobile Flash Player! Even more alarming was that statements around the dismissal of mobile Flash Player were always framed by statements declaring full support for HTML – even going so far as to point to HTML as the superior technology. This rightly upset a good number of Adobe’s strongest supporters in the Flash and Flex community. In addition, many well-known public figures at Adobe were part of a 750+ company-wide layoff. That’s 10% of the company’s total workforce. Ouch. For more information, I suggest reading Mike Chamber’s post about the situation. Fortunately, the rumor about the Flash Professional team has been declared false.

    Later that week Adobe posted more information about their plans for Flex and revealed that the SDK would be contributed to the Apache Foundation and maintained by Spoon, Adobe, and the community at large. Spoon, if you recall, is an organization established in April of this year which had the goal of working with Adobe to open the Flex SDK up for greater community involvement. This is the next logical step in that process. Keep in mind that Flex has actually been open source since 2006… so this has been a lengthy process. Having all of these projects (including PhoneGap) now under Apache is a good move; the Apache Foundation is respected and established. Not only has Adobe contributed the Flex SDK, but also the new generation Falcon compiler (and an experimental version of the compiler called Flacon JS), BlazeDS, and an internal set of testing tools. Flex will not shrivel and die there – Adobe has now made some truly AWESOME contributions to the open source community!

    To recap:

    • Adobe is halting development on the mobile web browser version of Flash Player for Android. This effectively places future versions of Android on the same level as iOS regarding Flash Player.
    • They are doing this as part of a massive reorg to shift resources to mobile AIR on Android and iOS. They are also focusing on tooling and contributions to open web standards. This is a good thing, overall.
    • IMPORTANT: Flash through mobile AIR on iOS, Android, Blackberry is going nowhere and is being given more resources. Again, this is what most developers have been working with – not mobile Flash Player in the browser.
    • Mobile Flash Player 11 is not going away on Android – but if Android handsets want to continue with new versions, they must license the source and compile it for their customers. It will remain available for download and use in the meantime.
    • Mobile Flash Player source is being licensed to those who wish to compile for their own platforms (like Blackberry does now). So mobile Flash Player may not be going away at all. It depends on the partners.
    • Adobe is also furthering efforts in HTML through projects like Dreamweaver, jQuery and WebKit contributions, Apache CallBack (PhoneGap), and notably their HTML/CSS/JS motion and interactivity solution Adobe Edge.
    • Flex is being placed under the Apache Foundation (where PhoneGap will also reside) and will recieve continued (hopefully envigorated) support by the Spoon project, Adobe itself, and possibly other corporate contributors.
    • An update for mobile Flash Player 11 will be provided for users of Android 4.0 (ICS) and Adobe will continue to support the runtime through security patches and bug fixes.
    • A mix of good and bad news – the good was absolutely ruined by the way the bad was communicated.

    Android 4.0 “Ice Cream Sandwich” was finally released in November. One of the great things about this announcement is that Google has released the source to both ICS and Honeycomb! All of the Android tablet manufacturers out there can finally take advantage of this resource. Even though Flash Player does not currently function with ICS, Adobe has committed to providing an update on Android that will get this working on the new OS.

    In Flash runtimes news, a lot of Stage3D resources and demos have been popping up on the web. For a good resource on using Stage3D for games, I would recommend having a look at Adobe Flash 11 Stage3D (Molehill) Game Programming Beginner’s Guide by Christer Kaitila. Amazingly enough, even renounced console publishers such as Square-Enix are having a serious look at Stage3D and have begun demonstrating some games built with these technologies. Flash Player 11.1 and AIR 3.1 were released as well. For those who want a concise, FREE resource to what is new in each of these runtimes; I suggest you check out a set of books published by O’Reilly as part of the Adobe Developer Library: What’s New in Flash Player 11 and What’s New in Adobe AIR 3. (Okay, yes, I am the author of these books but I do not get any royalties from them since they are free!)

    The web standards community set up movethewebforward.org which aims to get individuals involved in learning and contributing to standard web technologies in their own way. It’s a particularly good resource for those who may need some guidance along the current web landscape, though it does look like there’s something for everyone here.

    In a surprise move by HP, WebOS is going to be contributed to the open source community. It appears that the OS is far from dead, and HP hasn’t ruled out the manufacture of new devices which utilize the WebOS platform. Never count anyone out.

    Adobe hosted a small “Flex Community Summit” in San Francisco with 20 Flex developers from the community to discuss the future of the Flex framework. The stated goal of the Summit is to “fix the confusion, provide clarification, and rebuild trust.” Some of the most important takeaways from this discussion include:

    • There were robust apologies from Adobe executives around how the messaging was handled.
    • “For years to come Flex is going to be the best way to make applications for the web and desktop.” -Danny Winokur (Adobe)
    • Adobe’s involvement in future Flex will include “dozens of people”.
    • Apache Flex will target release runtimes.
    • AIR, Flex, and Flash Player (non-mobile) will continue to be supported.
    • “Flash isn’t just focused on gaming and video. Gaming helps push the envelop, but everyone can benefit from the improvements.”
    • “Adobe is committed to building applications with both Flex and HTML5, not just HTML5.”
    • “We have every interest that our runtime technology [Flash/AIR] is supported across as many platforms possible.”
    • Flash Catalyst has been discontinued. Design View in Flash Builder is slated for removal.
    • The new “Falcon” compiler will be ready for AS3 compilation in 2012. MXML compilation may be 2013.
    • Falcon is built to allow many back-end compilers such as FalconJS – the idea being that a developer can write in AS3/MXML and compile the code using Falcon, then cross-compile the output for JavaScript or other languages.
    • There was a great overview of the Apache Software Foundation process by Roy Fielding, an ASF founder.
    • Adobe will no longer sign RSLs, this will be done through Apache.
    • Proposal for Apache incubator is almost ready.
    • A Flex whitepaper will be published in January.

    There is still much to be done, but it is a good thing that things are moving forward in a positive way. 2012 will be an interesting year for sure.

    We close the year with rumors that Silverlight 5 will most likely be the final version of that runtime. While Silverlight never caught on the way Microsoft originally positioned it (as a “Flash killer”), it is sad that so many developers who invested their time in the technology could be left with an abandoned runtime. Silverlight did much to spur Adobe to action – ramping up development efforts for the runtimes and tooling. Without competing technologies, there is always the possibility of complacency… and that’s good for no one.


  4. Kah Shiu Chong says:
    January 3, 2012 at 1:45 pm

    Collision detection is a branch of algorithms that checks whether two shapes overlap. If you build physics or action games with ActionScript, you will certainly not escape acquaintance with this topic. This is the first of the series regarding collision detection. In this Quick Tip, we shall look at ActionScript’s built-in collision detection method, hitTestObject(), and write our own to detect overlap between two circles.


    Final Result Preview

    This is the final SWF we will create in this Quick Tip. Click the blue circle and drag it towards the green one. Once they overlap, the green circle will change its color; if you remove the blue circle again, the other will return to being green.


    Step 1: Bounding Box Checks

    Those who are aquainted with ActionScript 2.0 will definitely recognise the method, hitTest(). This command checks for overlap between two shapes, or between a shape and a single point. In ActionScript 3.0 it is split into two separate methods: hitTestObject() and hitTestPoint().

    We shall look at hitTestObject() first. This commnad generally suits collision detection for box-like shapes (squares, rectangles). A bounding box is drawn around shapes and when these bounding boxes overlap each other, hitTestObject() returns true.

    Check out the example below. Drag the blue box towards the green one. As they overlap, the green box’s shade darkens.

    I attach here the corresponding ActionScript that generates the above presentation. Box is a custom written class to easily generate square shapes. I’ve included the classes in the source folder; do refer to them. The important script for collision detection is highlighted below.

    
    
    package
    {
    	import flash.display.Graphics;
    	import flash.display.Sprite;
    	import flash.events.MouseEvent;
    	/**
    	 * Simple hitTest with boxes
    	 * @author Shiu
    	 */
    	[SWF(width = 400, height = 300)]
    	public class Simple extends Sprite
    	{
    		private var box1:Box, box2:Box;
    
    		public function Simple() {
    			box1 = new Box(0x0000FF); addChild(box1);
    			box1.x = 250; box1.y = 250;
    			box1.addEventListener(MouseEvent.MOUSE_DOWN, start);
    			box1.addEventListener(MouseEvent.MOUSE_UP, end);
    
    			box2 = new Box(0x00FF00); addChild(box2);
    			box2.x = 100; box2.y = 50;
    		}
    		private function start(e:MouseEvent):void {
    			e.target.startDrag();
    			e.target.addEventListener(MouseEvent.MOUSE_MOVE, check);
    		}
    		private function end(e:MouseEvent):void {
    			e.target.stopDrag();
    			e.target.removeEventListener(MouseEvent.MOUSE_MOVE, check);
    		}
    		private function check(e:MouseEvent):void {
    			if (e.target.hitTestObject(box2)) box2.color = 0x00AA00;
    			else				box2.color = 0x00FF00;
    		}
    	}
    }

    Step 2: Shortcomings of Bounding Boxes

    However, collision between circles cannot be effectively checked using this command. Check out the presentation below. Drag the blue circle towards the green one. Before the shapes collide, their bounding boxes already overlap and hitTestObject() is true. We need a more accurate solution.

    This problem is prevalent not only for collision detection between circles but non-square shapes generally. Observe the diagram below. For organic shapes that are difficult to resolve by polygons, we shall make use of pixel-precise collision detection.


    Various inaccurate collision detected through hitTestObject.

    Step 3: Distance Between Centers

    The solution to this problem is quite simple: we shall measure the distance between the centers of these circles. If the centers get close enough to each other, we shall flag collision as true. But how close is close enough?


    Distance between circles.

    Observe the diagram above. r1 refers to the radius of circle1 and r2 refers to the radius of circle2. The distance between circles is calculated on every frame. If (and only if) it is equal to or less than the sum of both radii (r1+ r2), then the two circles must be touching or overlapping each other.


    Step 4: Circle-Circle Collision Detection

    Here are the important ActionScript for the implementation of the concept above:

    
    
    minDist = circle1.radius + circle2.radius;
    
    
    
    private function check(e:MouseEvent):void {
    	var distance:Number = Math2.Pythagoras(circle1.x, circle1.y, circle2.x, circle2.y);
    	if (distance <= minDist) circle2.color = 0x00FFAA;
    	else circle2.color = 0x00FF00;
    }
    

    Step 5: Sample Solution

    Here is a sample of the solution. Drag the blue circle towards to the green one. As they overlap, you will see green’s color change. It returns to normal when both circles are not colliding.

    I have included the ActionScript implementation below.

    
    
    package
    {
    	import flash.display.Sprite;
    	import flash.events.MouseEvent;
    	/**
    	* Simple collision between 2 circles
    	* @author Shiu
    	*/
    	[SWF(width = 400, height = 300)]
    	public class Simple3 extends Sprite
    	{
    		private var circle1:Circle, circle2:Circle;
    		private var minDist:Number;
    
    		public function Simple3() {
    			circle1 = new Circle(0x0055AA, 30); addChild(circle1);
    			circle1.x = 250; circle1.y = 250;
    			circle1.addEventListener(MouseEvent.MOUSE_DOWN, start);
    			circle1.addEventListener(MouseEvent.MOUSE_UP, end);
    
    			circle2 = new Circle(0x00FF00, 30); addChild(circle2);
    			circle2.x = 100; circle2.y = 50;
    
    			minDist = circle1.radius + circle2.radius;
    		}
    
    		private function start(e:MouseEvent):void {
    			e.target.startDrag();
    			e.target.addEventListener(MouseEvent.MOUSE_MOVE, check);
    		}
    
    		private function end(e:MouseEvent):void {
    			e.target.stopDrag();
    			e.target.removeEventListener(MouseEvent.MOUSE_MOVE, check);
    		}
    
    		private function check(e:MouseEvent):void {
    		var distance:Number = Math2.Pythagoras(circle1.x, circle1.y, circle2.x, circle2.y);
    			if (distance <= minDist) circle2.color = 0x00FFAA;
    			else circle2.color = 0x00FF00;
    		}
    	}
    
    }
    

    Conclusion

    As you can see, the general principle of collision detection is to use mathematical formulae to check for overlappings between different shapes. Vector mathematics plays an important role too. Next to come is collision between a circle and a line. Thanks for reading and see you soon.


  5. Kah Shiu Chong says:
    January 3, 2012 at 2:02 pm

    In this tutorial, you will learn how to cast a field of view of a turret guarding a specific location. When an enemy is within the turret's field of view, the turret will shoot at them. Vector math will be used to help in implementing this field of view.


    Final Result Preview

    Let's take a look at the final result we will be working towards. Click on the turret at the bottom of stage to begin the simulation.


    Step 1: Field of View

    I’m sure most readers have used cameras. Every camera has a view angle, defined by the type of lens attached. There are narrow and wide view angles. View angles constrain the field of view into a sector. From a top-down position, they look like the diagram below. If you take a picture, eveything within the grayed area will be captured.

    Field of view: narrow and wide

    The turret's field of view in our simulation is like that of a camera. If there's an enemy within its field of view, a guard will respond (sound an alarm, take aim, shoot, etc).


    Step 2: Basic Concept

    Mathematical conditions to determine item within FOV

    The diagram above shows the field of view of turret. Usually the angle of view will be equal on both the left and the right. The radius will also be consistent throughout the sector. So to check whether an enemy is within a turret's field of view, these two mathematical conditions can be used:

    1. Distance between turret and enemy is less than radius.
    2. Angle from turret's line of sight to enemy is less than 30°.

    Step 3: Define Field of View Using Vector

    We shall use vector math to help us. In this case, the vectors in consideration are vLine2 and vLine3. We can:

    • Compare magnitudes of vLine2 and vLine3 to validate Condition 1 from Step 2.
    • Compare angle sandwiched between vLine2 and vLine3 to validate Condition 2 from Step 2.

    Using the formula of dot product between Vectors, we can find the angle sandwiched between two vectors. I have included a Flash presentation above to facilitate your understanding. Click on the buttons at the bottom to scroll through the frames.

    Here is the Actionscript in Vector2D (which I’ve used in previous tutorials, like this one) that does the job. Note that line 257 helps to determine whether the angle is on the negative or positive side. However, this is not going to help us much here as direction is not important. More explanations on this topic in the next part of this series.

    
    
    /**
     * Method to obtain the smaller angle, in radian, sandwiched from current vector to input vector
     * @param	vector2 A vector to bound the angle
     * @return Angle in radian, positive is clockwise, negative is anti-clockwise
     */
    public function angleBetween(vector2:Vector2D):Number
    {
    	//get normalised vectors
    	var norm1:Vector2D = this.normalise();
    	var norm2:Vector2D = vector2.normalise();
    
    	//dot product of vectors to find angle
    	var product:Number = norm1.dotProduct(norm2);
    	product = Math.min(1, product);
    	var angle:Number = Math.acos(product);
    
    	//sides of angle
    	if (this.vectorProduct(vector2) < 0) angle *= -1
    	return angle;
    }

    Step 4: Implementation

    I have included a presentation below that implements the concept of field of view. Feel free to click and drag the bigger gray circles around. Observe area covered by the field of view indicated by darker dots.


    Step 5: Important ActionScript

    If you'd like to see the ActionScript for the presentation above, feel free to open up AppFan.as from the source download – it’s commented to facilitate understanding. I shall only include here the important snippet that checks the conditions.

    I've highlighted the conditional statement that each of the little dots on the stage is evaluated against it to see if its within the highlighted area.

    
    
    //Calculate the magnitude and angle
    var vLine2:Vector2D = new Vector2D(b2.x - b1.x, b2.y - b1.y);
    var vLine3:Vector2D = new Vector2D(b3.x - b1.x, b3.y - b1.y);
    var ang:Number = Math.abs(vLine2.angleBetween(vLine3))	//Eliminate directional feature of angle
    var mag:Number = vLine2.getMagnitude();
    
    for each (var item:Ball in sp) {
    	var vParticle1:Vector2D = new Vector2D(item.x - b1.x, item.y - b1.y);
    
    	//Checking if falls within sector
    	//Condition: Magnitude less than mag, angle between particle ang vLine2 less than ang
    	 if(Math.abs(vLine2.angleBetween(vParticle1)) <ang
    	 && mag> vParticle1.getMagnitude()){
    		item.col = 0x000000;
    	}
    	//if outside of segment, original color
    	else item.col = 0xCCCCCC;
    	item.draw();
    }

    Step 6: Variations

    To add variation to the use of field of view, we can implement far and near attenuation. In fact, we just went through far attenuation. For far attenuation, enemies that are further away (further than the far attenuation distance) cannot be seen by the turret. For near attenuation, enemies that are too close (less than near attenuation) cannot be seen by turret. This may sound irrational, but imagine the turret sitting on a high cliff while the enemy sneaks right under the cliff.

    Okay, perhaps you are not convinced, so here is another example of different use. A guard carries a short sword, a bow and arrows. When an enemy is too far off, he may just want to keep a close eye on him. When the enemy comes within shooting range, he shoots arrows. When the enemy comes too close, he fights with short sword. You may even implement different types of guards: bowmen and swordsmen. Enemies within shooting range are dealt with by bowmen while those at at close range are dealt with by swordsmen.

    By understanding the conditions introduced in Step 2, variations can be introduced into our simulation or game.


    Step 7: Define Field of View Conditions

    I’ve included a Flash presentation below to showcase different cases and their corresponding set of conditions. Click on the buttons to check out the different cases.


    Step 8: Programming Field of View Conditions

    The following is a snippet of code for implementing the conditions as laid out in Step 7. You may want to view the whole source code in Region2.as to check out the whole implementation.

    
    
    //Checking done every frame
    private function move(e:MouseEvent):void
    {
    	//Calculate Vector from guard to enemy
    	var g_e:Vector2D = new Vector2D(enemy.x - guard.x, enemy.y - guard.y);
    	var angle:Number = r3.angleBetween(g_e);
    	//Conditions
    	var withinSector:Boolean = Math2.degreeOf(Math.abs(angle)) < sector;
    	var withinR3:Boolean = g_e.getMagnitude() < r3.getMagnitude();
    	var withinR2:Boolean = g_e.getMagnitude() < r2.getMagnitude();
    	var withinR1:Boolean = g_e.getMagnitude() < r1.getMagnitude();
    
    	//Difference example cases
    	if (example == 0) {
    		if (withinSector && withinR3) {
    			t1.text = "Within FOV"
    		}
    		else t1.text = "Beyond FOV"
    	}
    	else if (example == 1) {
    		if (withinSector && withinR3 && !withinR1) {
    			t1.text = "In between \nfar and near attenuation"
    		}
    		else t1.text = "Beyond FOV"
    	}
    	else if (example == 2) {
    		if (withinSector) {
    			if (withinR1) t1.text ="Sword attack"
    			else if (withinR2) t1.text = "Arrow shoot"
    			else if (withinR3) t1.text = "Keep observe"
    		}
    		else t1.text = "Beyond FOV"
    	}
    }
    
    //Swapping example cases in response to changes in context menu
    private function swap(e:ContextMenuEvent):void
    {
    	//swap example
    	if (e.target.caption == &quot;Basic FOV&quot;) example = 0;
    	else if (e.target.caption == &quot;Far/Near Attenuation&quot;) example = 1;
    	else if (e.target.caption == &quot;Observe/Arrow/Sword&quot;) example = 2;
    
    	//Redraw region indicating detection area
    	drawRegion();
    }
    

    Step 9: Implementation

    Here's an implementation of ideas explained in Step 6. Click on the black circle and drag it aroud the stage to check whether it’s sitting within the visible region. Right-click on stage to pop context menu out, then select from "Basic FOV", "Far/Near Attenuation" and "Observe/Arrow/Sword" to check out the different examples.


    Step 10: The Scenario

    Now to put into context whatever we have learnt, we are going to create a simulation. Here's the scenario:

    A turret is stationed at one end of the stage. Its role is to eliminate as many troops that invade its space as possible. Of course, turret will have to see those troops (within field of view) in order to shoot lasers – and bye-bye troops. Since it can only shoot a beam of laser at any instance, it’s going to choose the closest enemy in sight.

    On the other hand, troops will try to successfully cross to the other side. They will have to cross a river and, as they do, they will slow down. Now these troops are going to respawn on top of stage whenever they die or go out of stage.

    Image depicting scenario 1

    Step 11: Basic Setup

    The implementation of this example will be hard-coded. The basic setup is as below. On initialisation we will draw the graphics of elements (river, troops, turret) and position then nicely. On clicking on the purple turret, animation will start. On every frame we will see them animate according to the behaviours of each element.

    
    
    public function Scene1() {
    	makeTroops();
    	makeRiver();
    	makeTurret();
    	turret.addEventListener(MouseEvent.MOUSE_DOWN, start);
    	function start ():void {
    		stage.addEventListener(Event.ENTER_FRAME, move);
    	}
    }
    private function move(e:Event):void {
    	behaviourTroops();
    	behaviourTurret();
    }
    

    Below are the variables of this class.

    
    
    private var river:Sprite;
    
    private var troops:Vector.<Ball>;
    private var troopVelo:Vector.<Vector2D>;
    
    private var turret:Sprite;
    private var fieldOfView:Sprite;
    
    private var lineOfSight:Vector2D = new Vector2D (0, -300);	//line of sight facing north
    private var sectorOfSight:Number = 	20			//Actually half of sector, in degrees
    

    Step 12: Draw and Position River

    Drawing and positioning river. Pretty simple.

    
    
    private function makeRiver():void {
    	river = new Sprite; addChild(river);
    
    	//Specify the location & draw graphics of river
    	with (river) {
    		x = 0; y = 150;
    		graphics.beginFill(0x22BBDD, 0.2);
    		graphics.drawRect(0, 0, 500, 50);
    		graphics.endFill();
    	}
    }

    Step 13: Draw and Position Troops

    Drawing troops will be simple. However, I wanted a "V" formation on troops. So I position the troop at the bottom of "V" first, followed by troops on both sides of its wing. You may want to adjust its center position through center and the spacing between troops through xApart and yApart. Note that troops and its corresponding troopVelo share the same index. All troops are heading south.

    
    
    private function makeTroops():void {
    	troops = new Vector.<Ball>;		//Initiate troops
    	troopVelo = new Vector.<Vector2D>;	//initiate velocity
    
    	//local variables
    	var center:Vector2D = new Vector2D(stage.stageWidth * 0.5, 150);
    	var xApart:int = 20; var yApart:int = 15; 
    
    	//Locating troops & velocities
    	var a:Ball = new Ball; stage.addChild(a); troops.push(a);
    	a.x = center.x; a.y = center.y;
     	//troops heading south
    	var aV:Vector2D = new Vector2D(0, 1); troopVelo.push(aV);	
    
    	for (var i:int = 1; i < 11; i++) {
    		var b:Ball = new Ball; stage.addChild(b); troops.push(b);
    		b.x = center.x + i * xApart; b.y = center.y - i * yApart;
    		var bV:Vector2D = new Vector2D(0, 1); troopVelo.push(bV);
    
    		var c:Ball = new Ball; stage.addChild(c); troops.push(c);
    		c.x = center.x - i * xApart; c.y = center.y - i * yApart;
    		var cV:Vector2D = new Vector2D(0, 1); troopVelo.push(cV);
    	}
    }

    Step 14: Draw and Position Turret

    Here, we shall draw, position, and orient the turret and its field of view to face north towards the enemy. Note that the line of sight is facing north.

    
    
    private function makeTurret():void {
    	//instantiate, locate, orient turret
    	turret = new Sprite; stage.addChild(turret);
    	turret.x = stage.stageWidth * 0.5,
    	turret.y = stage.stageHeight;
    	turret.rotation = -90;
    	turretRot = 2;				//rotation speed
    
    	//Draw turret graphics
    	var w:int = 30; var h:int = 10;
    	turret.graphics.beginFill(0x9911AA);
    	turret.graphics.lineStyle(2); turret.graphics.moveTo( 0, -h / 2);
    	turret.graphics.lineTo(w, -h / 2); turret.graphics.lineTo(w, h / 2);
    	turret.graphics.lineTo(0, h / 2); turret.graphics.lineTo(0, -h / 2);
    	turret.graphics.endFill();
    
    	//Setting data for field of view's graphics
    	var point1:Vector2D = new Vector2D(0, 0);
    	var point2:Vector2D = new Vector2D(1, 0);
    	var point3:Vector2D = new Vector2D(0, 0);
    	point1.polar(lineOfSight.getMagnitude(), Math2.radianOf(sectorOfSight));
    	point2.setMagnitude(lineOfSight.getMagnitude()/Math.cos(Math2.radianOf(sectorOfSight)));
    	point3.polar(lineOfSight.getMagnitude(), Math2.radianOf(-sectorOfSight));
    
    	//instantiate, locate, orient field of view
    	fieldOfView = new Sprite; addChild(fieldOfView);
    	fieldOfView.x = turret.x; fieldOfView.y = turret.y;
    	fieldOfView.rotation = -90;
    
    	//draw turret's field of view
    	fieldOfView.graphics.beginFill(0xff9933, 0.1);
    	fieldOfView.graphics.lineStyle(1);
    	fieldOfView.graphics.moveTo(0, 0);
    	fieldOfView.graphics.lineTo(point1.x, point1.y);
    	fieldOfView.graphics.curveTo(point2.x, point2.y, point3.x, point3.y);
    	fieldOfView.graphics.lineTo(0, 0);
    	fieldOfView.graphics.endFill();
    }

    A little detail here on the drawing the line of sight. I’ve included image below for clarification:

    Image to clarify points in drawing FOV

    Step 15: Troops' Behaviour

    Troops will be animated across time. Here's their behaviour. Note that the last two lines of code are commented. If you would like dead troops to be removed from animation, you may uncomment them.

    
    
    //troops' behaviour
    private function behaviourTroops():void
    {
    	//for each troop
    	for (var i:int = 0; i < troops.length; i++) {
    
    		//If troop reach bottom of screen, respawn on top of screen
    		if (troops[i].y > stage.stageHeight) {
    			troops[i].y = 0; troops[i].x = Math.random() * (stage.stageWidth - 100) + 100;
    		}
    		//if wading through river, slow down
    		//else normal speed
    		if (river.hitTestObject(troops[i])) troops[i].y += troopVelo[i].y*0.3;
    		else troops[i].y += troopVelo[i].y
    
    		//If troop is dead ( alpha < 0.05 ), respawn on top of screen
    		if (troops[i].alpha < 0.05) {
    			troops[i].y = 0; troops[i].x = Math.random() * (stage.stageWidth - 100) + 100;
    			troops[i].col = 0xCCCCCC; troops[i].draw(); troops[i].alpha = 1;
    			//stage.removeChild(troops[i]); troops.splice(i, 1);
    			//troopVelo.splice(i, 1);
    		}
    	}
    }

    Step 16: Turret’s Behaviour

    The turret will guard its post by panning its field of view around, but within certain angles. Here, I’ve defined the panning angle to be between -135 and -45 (using Flash angles). If there's an enemy within sight, it will attack it. But if there's more than one enemy, it's going to choose the closest to attack.

    
    
    //turret's behaviour
    private function behaviourTurret():void
    {
    	//rotate turret within boundaries of -135 & -45
    	if (turret.rotation > -45)	turretRot = -2
    	else if (turret.rotation < -135) turretRot = 2
    
    	//shoot closest enemy within sight
    	graphics.clear();
    	if (enemyWithinSight() != null) {
    
    		//closest enemy in sight
    		var target:Ball = enemyWithinSight();
    		target.col = 0; target.draw(); 	//turns to black &
    		target.alpha -= 0.2;		//health deteriorates
    
    		//orient turret towards enemy
    		var turret2Target:Vector2D = new Vector2D(target.x - turret.x, target.y - turret.y);
    		turret.rotation = Math2.degreeOf(turret2Target.getAngle());
    
    		//draw laser path to enemy
    		graphics.lineStyle(2);	graphics.moveTo(turret.x, turret.y);	graphics.lineTo(target.x, target.y);
    	}
    
    	//no enemy within sight, continue scanning
    	else { turret.rotation += turretRot }
    
    	//turn field of view and line of sight of turret according to turret's rotation
    	fieldOfView.rotation = turret.rotation;
    	lineOfSight.setAngle(Math2.radianOf(turret.rotation));
    }

    Step 17: Getting Closest Enemy

    The turret will locate the closest enemy in its field of view and react by shooting a laser at it. To see how it finds the closest enemy, check out the ActionScript implementation below.

    
    
    //return the closest enemy within sight
    private function enemyWithinSight():Ball {
    	var closestEnemy:Ball = null;
    	var closestDistance:Number = lineOfSight.getMagnitude();
    
    	for each (var item:Ball in troops) {
    		var turret2Item:Vector2D = new Vector2D(item.x - turret.x, item.y - turret.y);
    
    		//check if enemy is within sight
    		//1. Within sector of view
    		//2. Within range of view
    		//3. Closer than current closest enemy
    		var c1:Boolean = Math.abs(lineOfSight.angleBetween(turret2Item)) < Math2.radianOf(sectorOfSight) ;
    		var c2:Boolean = turret2Item.getMagnitude() < lineOfSight.getMagnitude();
    		var c3:Boolean = turret2Item.getMagnitude() < closestDistance;
    
    		//if all conditions fulfilled, update closestEnemy
    		if (c1 && c2&& c3){
    			closestDistance = turret2Item.getMagnitude();
    			closestEnemy = item;
    		}
    	}
    	return closestEnemy;
    }

    Step 18: Launching Simulation

    You may now press Ctrl + Enter in FlashDevelop and observe this simulation. Click the turret to start the demo below.


    Step 19: A Step Further

    We can make use of this understanding to:

    • Implement a field of view for enemies.
    • Implement more turrets.
    • Introduce variation to the field of view as explained in Step 9.

    …and so on.

    Hopefully, this will spark some ideas and perhaps help in your next simulation or game.

    Conclusion

    Thanks for reading. As usual, do drop a comment to let me know if this has been helpful to you. I'll be writing the next tutorial to check out how enemies can stay out of turret's field of view by "hiding" behind obstacles. Stay tuned.


  6. Michael James Williams says:
    January 3, 2012 at 2:19 pm

    Merry Quizmas! This month, I’m quizzing you on your understanding of two popular formats for data used by web apps: JSON and XML.


    Let’s Get Quizzy

    Having Trouble?

    If you get stuck, take a look at our previous posts: Understanding JSON and AS3 101: XML.


    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!


  7. David Appleyard says:
    January 3, 2012 at 2:22 pm

    The holidays are upon us, and we’re feeling festive at Tuts+ this weekend! We’d like to take this opportunity to say a huge Christmas thank you to all our readers, and wish you a very Happy Holiday. Read on for a video message from the HQ team, and a few freebies from around the Tuts+ and Envato network!


    A Message from Envato HQ

    Although the Tuts+ team is spread over the globe, Envato HQ is where much of the Tuts+ magic happens! It isn’t looking traditionally Christmassy in Melbourne at the moment, but we have a special holiday message from everyone at head office:

    From everyone at Envato we want to wish you a Happy Holidays and look forward to seeing you all refreshed and ready for another big year in 2012! From Envato HQ to the community, we’ve created a little video to share the holiday cheer. Enjoy!

    Music is Kids Holiday Theme by AudioJungle Author CraigHall


    Gift Guides & Freebies!

    Wondering what to buy your fellow geek this Christmas? Never fear! You may have left it it a little late, but our holiday gift guides can still come in handy. Here are a few great places to start:

    • The Official 2011 Nettuts+ Holiday Gift Guide
    • 30+ Gift Ideas for Browser App and Browser Game Developers
    • 10 Last-minute Gift Suggestions for the Musician in Your Life
    • 36 Great Holiday Gift Ideas For The Cg Artist!
    • The Official 2011 Phototuts+ Holiday Gift Guide
    • 20+ Great Gift Ideas for Any WordPress Developer

    We also have a couple of exclusive freebies and discounts, just in time for the holidays:

    • Get $6 Off Our New Rockable Book: “How to Record Great Music”
    • Exclusive Freebie: 50 Crisp Web UI Icons

    The Christmas Freelance Freedom Comic

    The “holiday jingle” comic encapsulates everything that we love and hate about freelancing. Don’t forget to sing along to the “Jungle Bells” theme music as you read it…!

    You can also enjoy the whole back catalog of Freelance Freedom comics over at FreelanceSwitch.


    AppStorm Giveaways

    We have two fantastic competitions running over at the AppStorm network over the holiday period, and there’s still time to get your entry in to stand a chance of winning:

    1. Business Productivity Bundle Giveaway —Each bundle includes a license to Daylite and Billings Pro – it’s the perfect combination for getting your business organised and making money!
    2. The AppStorm Holiday ’11 Video Game Giveaway — In the spirit of this season we’ve hand picked a few critically acclaimed, and award-winning, games released over this year to give away to our readers!

    Merry Christmas, and Happy New Year!

    All that’s left is to wish you a very happy holiday on behalf of everyone at Tuts+! We hope you’ve enjoyed everything that we’ve had to share this year, and look forward to publishing thousands more top-quality tutorials, articles, freebies, and resources in 2012.

    Here’s to another exciting year at Tuts+, and thank you for joining us on the journey!


  8. Matt Pearce says:
    January 3, 2012 at 3:01 pm

    Twice a month, we revisit some of readers’ favorite posts from throughout the history of Activetuts+. Please enjoy this festive tutorial from Christmas past!

    Ever wanted give your Flash design an extra dimension? Using Electric Rain’s brilliant 3D software, this basic tutorial will give you an introduction in using Flash and Swift 3D together to create some fantastic graphics and animations.


    Swift 3D Flash Render

    Final Result Preview

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

    Step 1: New Flash File

    Create a new Flash file, it doesn’t matter what version of ActionScript you use; we’re only using Flash at the moment to create the graphics to export to Swift 3d.

    Swift 3D Flash Render

    Step 2: Creating the Graphics

    Using whatever tools you feel comfortable with, create the basic shapes of the Santa and his Skidoo. I used the pen and pencil tool to create the basic shapes, the fewer anchor points and detail you use the better. This will speed up the time it takes for Swift 3d to import the objects you have created in Flash, and also make the 3d models easier to modify and render in Swift 3d.

    An important thing to know is that Swift doesn’t like gradient fills or strokes created in Flash. So just use single color fills and make sure you delete any strokes/outlines.

    Swift 3D Flash Render

    Step 3: Exporting Your Graphics

    File > Export > Export Image > Adobe Illustrator… I’ve saved my file as “father_xmas.ai”.

    Swift 3D Flash Render

    Step 4: The Swift 3d Interface

    I could produce a whole tutorial on the in’s and out’s of Swift 3d, but just to give you an idea of what Swift 3d is like and how easy it is to use I’ve included an image of the interface. The interface is made up of these main elements …

    • Property Tools.
    • Lighting Tools.
    • Tracking Tools.
    • Gallery Tools.
    • Edit Tools.
    • Animation tools.
    • Hierarchy Tools.
    • Editor Selector.

    As this is only a simple beginner’s tutorial we’ll be using most of these tool and functions, but nothing too complicated…

    Swift 3D Flash Render

    Step 5: Importing Your Graphics

    1. Open Swift 3d.
    2. File-Import.
    3. Select your .AI file you exported from Flash.
    4. Select "Open".

    It will take a minute for Swift to import all the graphics and data.

    Swift 3D Flash Render

    Step 6: Our Imported Graphics

    As you can see, our graphics have come in pretty much as we created them in Flash. Swift is good at creating these extrusions on its own using the "Extrusion Editor", but I find it easier to draw in Flash, so I use Flash to create all my Extrusions.

    Swift 3D Flash Render

    Step 7: Adjusting Our Layout in Swift 3d

    First thing we want to do is adjust the size of our layout. In the "Property Tools" change the following settings:

    1. Set the layout in this tutorial to 600×600 pixels.
    2. Change the "Nudge Increment" to "0.01" to allow greater accuracy when we come to move the objects around later on.
    Swift 3D Flash Render

    Step 8: Viewing Imported Graphics

    The first thing to do is change our first viewport to a "Default Target Camera" View, this allows us to rotate and view our Santa freely in any direction.

    1. Select the camera view in the top left corner of one of the viewports.
    2. Change it to "Default Target Camera".
    3. If you hold down the "cmd" key on a Mac or the "Ctrl" key on a PC, place your cursor anywhere in the Default Target Camera Viewport and you can move your mouse to rotate the view port to get a good look at what you have created.
    4. If you hold down the right-click button on your mouse, cmd/Ctrl key and drag, it allows you to zoom in and out with the Default Target Camera view.

    These cmd/Ctrl/right-click techniques do take a bit of getting used to, but stick with it and it will soon become second nature to you.

    As you can see they are all pretty much the same depth at the moment, we can easily change that, but the first thing to do is name all our objects so we know our arms from our legs!

    Swift 3D Flash Render

    Step 9: Viewing Objects

    I thought it might be worth pointing out how to move your focus point in the "Default Target Camera". This red circle with a green vertical line through it is your camera focus/target point. If you click in the middle of this shape and drag, it will move the target position of your camera.

    Swift 3D Flash Render

    Step 10: Un-Grouping Imported Graphics

    Swift 3d has grouped all our objects and I have 24 objects in my "Hierarchy Menu". First thing to do is "Ungroup" these objects/extrusions. To do this select "Arrange", then "Ungroup". Click anywhere in a viewport and your objects will appear in a list called Extrusion, Extrusion 1, 2, 3 etc…

    Swift 3D Flash Render

    Step 11: Re-naming Imported Graphics

    1. You can click on any Extrusion in the "Hierarchy" box or you can click on the actual object in the "Viewport".
    2. Open the "Property Tools".
    3. Select "Object" from the menu.
    4. Simply type in the name of that object, then press "Enter".
    5. Repeat this for all the extrusions.

    I know it’s a bit tedious but it will help you later on!

    Swift 3D Flash Render

    Step 12: Creating Parent and Child Relationships

    To parent the foot to the leg for example is easy. Simply drag the RightFoot onto the RightLeg to create the parent child relationship, do the same for the arms, hands and cuffs and the same for the rest of the objects as I’ve done here.

    Swift 3D Flash Render

    Step 13: Improving the Quality of our Model

    This bit is optional but I like to improve the quality of my models. This can increase the file size of the final image or animation, but as ours is relatively simple it shouldn’t matter too much. To do this got to the "Property Tools"

    1. Select "Bevels".
    2. Drag the "Smoothness" slider to the far right "Smooth".
    3. Drag the "Mesh Quality" slider to the far right "High".
    Swift 3D Flash Render

    Step 14: Moving and Positioning Objects

    You can move your objects into position a number of ways:

    1. Using the "Property Tools" you can accurately position your objects by adjusting the X, Y, Z values using numbers or using the sliders.
    2. Use your arrow keys to nudge the object.
    3. Easiest way…drag to move your object and switch between view ports until you are happy with the placement.
    Swift 3D Flash Render

    Step 15: The Finished 3d Model

    This is what I ended up with as my final model in Swift 3D. Father Xmas sitting on a skidoo! I used a couple of the ski supports as handle bars and colored them red. We’re nearly there now, just a few more steps and we’re done.

    Swift 3D Flash Render

    Step 16: Re-coloring our Model

    The files coloring should look pretty much the same as the graphics you created in Flash. However, I tend to re-color them in Swift as I find that they are a bit too glossy for my liking. To change the color of an object..

    1. Go to the “Material” section in the “Property Tools”.
    2. Double-click on the little colored ball.
    3. This will bring up the “Edit Material” Box. There are loads of tools for you to play around with in here, but all I have done is reduce the "Highlight Strength" and "Highlight Size" by dragging them to the far-left.
    4. Click on "Generate Preview" to update the preview thumbnail.
    5. To change a color simply double-click on the large color bar and adjust accordingly.

    Do this for all or none of your objects, it’s up to you.

    Swift 3D Flash Render

    Step 17: Adding a Floor

    To add a floor to place your model on you need to create a plane, this will allow the shadows to be cast onto a surface/floor.

    1. Select the "Create Plane" from the top toolbar. You might need to rotate your view port to see it, but don’t worry if you can’t see it just yet.
    2. Go to the "Property Tools" and select "Plane".
    3. Change the size of the plane to 1000.00 by 1000.00.
    4. Re-color the floor using the same technique in Step 16.
    Swift 3D Flash Render

    Step 18: Lighting

    First we want to remove Swift’s default lighting, or if you want you can keep it as is… I just prefer to add my own lighting setup.

    1. First thing to do is make sure you are in the "Top" view port (you can’t edit the lighting if you are in the "Default Target View").
    2. Then, in turn click on each of the lights in the "Lighting Tools" and delete them. You’ll know when the light is selected as it turns red instead of yellow.
    3. Then hit the "-" (shown here in a red box) or the "Delete Button". Do this for each of the lights.
    Swift 3D Flash Render

    Step 19: Adjusting the Lighting

    Now we’re ready to create our own lighting. Still in the "Top View":

    1. Select the "Create Trackball Point Light" as shown below.
    2. Then in the "Property Tools", select the "Point Light" you have just created.
    3. Double-click in the "color box" and change it to a mid gray – (this will tone down the brightness of the light).
    4. Leave the light size at 0.00, turn off everything in the "Options" but leave it "Active".
    Swift 3D Flash Render

    Step 20: Adding More Lights

    OK, we need to create more lights by doing exactly the same as "Step 19". The new light will appear over the top of the light you have just created, so we need to move it to another position.

      Make sure the "Lock Spin" button is toggled to "On" This will rotate around a fixed axis.

    1. Make sure you have "Rotation Increment" set to 90 degrees.
    2. Then simply click drag the second light you’ve created around the trackball.
    3. Do this 3 times so that you have 4 equal lights around the trackball (Name your lights if you wish …Front, Left, Right, Back).
    4. Create 1 more light. This will be our top light and will cast the shadows in the scene.
    5. Make sure the "Lock Vertical" toggle is active and drag it up to the top of the scene.
    6. With this light you want the "Shadows" to be active.
    Swift 3D Flash Render

    Step 21: Rendering Santa

    If you’re using the trial version you won’t be able to export any of your renderings, but you can screen grab what you have done and save it out as a bitmap and crop it in Photoshop. If you have the full working version, Swift 3d comes with a built in Smart Layer rendering function, which separates our graphics/animations into layers. This means that things like shadows, moving objects and transparency layers are separated onto their own layer to help reduce file sizes and makes editing in Flash easier.

    Swift can render to both Vector and Bitmap formats, can export to all the standard .swf, .AI and the .SWFT (Smart Layer) for vector formats and render to .png, .jpeg etc in the bitmap formats.

    OK here we go…

    Make sure the "Default Target View" is active in the "Scene Editor" (swift will render the active viewport by default).

    1. Click on the "Preview and Export Editor".
    2. Once in the Preview and Export Editor, under the "General" Settings set the Compression to "Quality" and the Curve Fitting to "Lines".
    3. Under the Fill options "Fill Type" select "Area Gradient Shading".
    4. Make sure "Include Shadows" is selected.
    5. Adjust the shadow density to something similar as shown.
    Swift 3D Flash Render

    Step 22: Rendering Santa Continued..

    1. Click on the "Generated Selected Frames", it will take a few minutes to render.
    2. If you are happy with what you see rendered click "Export Selected Frame".
    3. Export the frame to a location of your choice, and name it what ever you want.
    Swift 3D Flash Render

    Step 23: Importing Santa into Flash

    1. Open Flash.
    2. Create a new document.
    3. Set the stage to 600×600 pixels.
    4. Choose "File"-"Import".
    5. Locate the Swift 3d .SWFT file we exported from Swift 3d.
    6. Click on it to import it to either the "Stage" or "Library".
    7. If you imported it to your library simply drag it an position it on stage.

    All done!

    Conclusion

    In this tutorial I’ve shown you the basics of using Flash and Swift 3d together to add an extra dimension to your Flash design work. There’s certainly a lot to cover with Swift 3D and I hope this gives you an idea of what you can achieve using these two pieces of software together. Once you’ve explored the capabilities of Swift 3D I’m sure, like me, you’ll find you use it all the time.

    I hope you liked this tutorial, thanks for reading and have avery merry Christmas!


  9. Dimitar Apostolovski says:
    January 3, 2012 at 3:11 pm

    Sometimes you may find yourself needing to modify the behavior of a component for a user input event. This article will explain how to do so by modifying the event object in-flight, before it’s processed by the component. That’s right, you can lie and cheat. In code.


    Example

    Suppose we have a List component for the user to select multiple items from. We have set its allowMultipleSelection property to true, which would allow it to have more than one selected items (hence the name). However, this still requires that the user holds down the Ctrl key, while clicking, to select multiple items. When a single selected item is the exception, not the rule, it would be better if we didn’t make the user hold the Ctrl key every time!

    The component determines whether the user is holding the Ctrl key by examining the ctrlKey property of the MouseEvent event object. In the above example, we’re tricking the component, by making it appear that the Ctrl key is pressed.

    Let’s look at how this is done…


    Step 1: Set Up the Flash Document

    If you already know how to create Flash applications (you probably do) you can skip reading this step, but keep in mind that the existence of an instance of a List component is assumed in next steps. Just in case, let’s briefly explain the creation of the project.

    Create a new FLA (here named htefExample.fla) and a new document class ActionScript file (here named htefExample.as).

    Set the properties of the FLA file and link the document class.


    The width of the FLA is set to 300, the height to 200 and the ‘Class’ input field is set to ‘htefExample’”.

    Drag a List component from the Components panel to the Library.


    In the Library the List symbol and its assets are contained.

    Write the document class (htefExample.as).

    
    
    package{
    
    	import flash.display.Sprite;
    
    	import flash.events.MouseEvent;
    
    	import fl.controls.List;
    
    	import fl.data.DataProvider;
    
    	public class htefExample extends Sprite{
    
    		private var list:List;
    
    		function htefExample(){
    			// create an instance
    			list = new List();
    			// and set some properties
    			list.width = 200;
    			list.x = 50;
    			list.y = (200-list.height)/2;
    
    			// set allowMultipleSelection
    			list.allowMultipleSelection = true;
    
    			// add data
    			list.dataProvider = new DataProvider([{label:"One", data:1},
    						  {label:"Two", data:2},
    						  {label:"Three", data:3},
    						  {label:"Four", data:4},
    						  {label:"Five", data:5}]);
    
    			// add to display list
    			this.addChild(list);
    
    		}
    
    	}
    
    }
    

    Step 2: Add an Event Listener to the Capturing Phase

    The signature of the addEventListener method is:

    addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void

    To add a listener to the capturing phase, set the third parameter (useCapture) to true.

    
    
    list.addEventListener(MouseEvent.CLICK, hackMouseListener, true);
    

    Step 3: Define the Contents of the Listener Function

    In the body of the function, set the ctrlKey property to true.

    
    
    private function hackMouseListener(e:MouseEvent):void{
    	// set ctrlKey property
    	e.ctrlKey = true;
    }
    

    How It Works

    Flash Player has a model for dispatching events and calling event listeners called the event flow. For display-related events, the Player doesn’t dispatch the event directly to the target object, but instead injects it at the top-level display object: the stage.

    We can visualize the event traveling from the stage down the hierarchy to the target object. This is called the capture phase.

    At the target, the event is in the target phase.

    Then, the event ‘bubbles up’ back to the stage. This is the bubbling phase.

    The Flash Player event flow.

    This imaginary trip determines the order in which the listener functions are called. The useCapture parameter in the addEventListener method states our desire about which direction we want our function to be activated: on the capturing way down (value: true) or bubbling way up (value: false – the default).

    What is interesting is the fact that the event object that is passed as an argument to the listener functions is the same one. So, if we change some of its properties, the listeners further down the event flow will get the same object, now modified!

    In the example above, when we registered the hackMouseListener function to use the capture phase, we made sure that we’ll get the event on its “way down”, so to speak. That function will be called before the list’s listeners which are registered to the target/bubbling phase on the component itself. When the list’s code inspects the ctrlKey property it will find that it is set to true, indicating that the user pressed the Ctrl key.

    Or did he?


    Conclusion

    You now know how to make a List component multi-select with just a simple event listener. You can use this on other list-based components like DataGrid. Don’t forget to set the allowMultipleSlection property.

    More importantly, however, is that (hopefully) you’ve learned something new about the Flash event flow, about the useCapture parameter, event phases and how to use this marvelous (and a bit unconventional) method to bend events to your needs.

    Hope you enjoyed it. Thank you for reading!


  10. Tyler Seitz says:
    January 3, 2012 at 3:44 pm

    When a user first opens up a Flash game, their initial impression is based upon the menu that they see. Unfortunately, many games’ menus are dull, plain and static. This is terrible news! A lot of players will just close the game before even playing it, and move on to another. Don’t let this happen to you!


    Final Result Preview

    Take a look at the menu we’ll be building:

    Obviously, in a full game, the different menu screens would contain different buttons, text, and submenu items!


    Introduction: What is a Dynamic Menu?

    Before we learn what a dynamic menu is we must first learn what a static menu is.

    A static menu can be described by the definitions of the two words it is made up of: “static”, meaning lacking in change, and “menu”, meaning a list of available options or choices. Therefore a static menu has an interface of options or choices that is lacking in change.

    Conversely, the word “dynamic” means to continuously cause change within a system or process. So in the simplest terms a dynamic menu continuously updates the interface of given options or choices.


    Step 1: Setting Up

    The first thing that we are going to need to create is a new Flash File(ActionScript 3.0), set its width to 650px and height to 350px, and set the frames per second to 60. Instead of changing the background color leave it as white; later on in the tutorial we will create a background.

    Now that we have the basic Flash File set up we can save it; you can name yours whatever you please. I just named mine MenuAccordion.fla.

    In the next section we will create the eight MovieClips required for the menu; here is a list of all the colors and their hexidecimal codes that will be used throughout the tutorial:

    • White – #FFFFFF
    • Gold – #E8A317
    • Light Gold – #FBB917
    • Blue – #1569C7
    • Light Blue – #1389FF
    • Green – #347235
    • Light Green – #3E8F1B
    • Red – #990000
    • Light Red – #C10202
    • Matte Grey – #222222

    Step 2: Creating the MovieClips

    To start off we need to create one main background color, four “bar” MovieClips (these are the ones that will be clicked on) and four background MovieClips (these will slide out after a bar is clicked).

    First, right-click the stage and choose Grid, then select Show Grid – by default it will create a 10px by 10px square grid accross the stage. To make your life easier right-click again and select Snapping > Snap to Grid. Now we are ready to start drawing!

    Select the Rectangle tool and draw a Matte Grey background over the whole stage. Name the layer Background and lock it. Next, create a new layer and name it Menu. Your timeline and stage should look something similar to this now:

    first look at the timeline

    first look at the stage

    Next we will create one bar MovieClip; to make things easier we will just duplicate it to form four MovieClips and change the color of each.

    Select the rectangle tool once again, and draw a 30px by 350px rectangle with no stroke. Right-click the fill and select Convert to Symbol…. Name it goldBar, make sure the type is MovieClip and the registration point is in the top-left corner. Double-click the MovieClip on the stage to edit it.

    Right-click the first keyframe in the timeline and go to actions, type in a simple stop(); command to prevent the MovieClip from cycling through frames. Next, right-click the second frame and select Insert Keyframe. It is up to you what you would like to write in each fill; only thing to remember is that if your are writing on a 90 degree angle the text may appear invisible if you have the text set to dynamic. Personally I just broke apart the text until it became a fill, and I drew an arrow that was pointing opposite directions on each frame:

    A frame comparison of the gold bar

    Now that we have one bar completed we can right-click it in the library and select Duplicate Symbol…. Make three copies of it and name them blueBar, greenBar and redBar, respectively. Then just edit their fill colors and change the text. Voila! We have four bar MovieClips.

    Now we can begin on the background MovieClips which we will create and duplicate in the same way. Select the rectangle tool again and draw a rectangle of 560x350px. Convert it to a symbol, name it goldBackground, and make sure that the type is a MovieClip and the registration is in the top-left corner. Then just duplicate it three times and name the new MovieClips blueBackground, greenBackground and redBackground respectively.

    Your rectangles should look very simple, like this:

    The goldBackground

    There is only one more MovieClip to create, I promise! Go to the Insert menu and select New Symbol; name it menuAccordionMC, set the type to MovieClip and put the registration point in the top-left corner (because our last MovieClips had this too). Next, check the box that says Export for ActionScript: the class name should be MenuAccordionMC with the capital at the beginning.


    Step 3: Positioning the MovieClips

    In the previous section we created all the MovieClips required, and now we need to position them!

    Delete any MovieClips on the stage if they are on still there. Open your menuAccordionMC from the Library, and create seven more layers in its timeline. Now name them in the following order from top to bottom:

    • goldBar
    • blueBar
    • greenBar
    • redBar
    • goldBackground
    • blueBackground
    • greenBackground
    • redBackground

    Now drag and drop each MovieClip from the library to its corresponding layer. The easiest way to position all of these will be to lock all of the layers besides the one with the MovieClip you are currently positioning.

    Start with the goldBar and set its x and y coordinates to (0,0). Next the blueBar with the coordinates (30,0), then the greenBar with (60,0), and finally the redBar with (90,0).

    Time for the backgrounds: the goldBackground‘s coordinates are (-530,0), the blueBackground‘s coordinates are (-500,0), the greenBackground‘s coordinates are (-470,0) and the redBackground‘s coordinates are (-440,0).

    Your MovieClip should look like this now, and the (0,0) coordinate should be in the top-left corner of the goldBar MovieClip where the white plus is in the image:

    What you should see in the menuAccordionMC

    Step 4: Identifying the MovieClips

    Before we can begin coding there is one more thing we have to do: give the eight inner MovieClips instance names.

    Open up the the menuAccordionMC for the final time then select each MovieClip and make its instance name the same as its MovieClip name. So goldBar’s instance name would be goldBar, greenBackground’s instance name would be greenBackground, and so on. After this is done we can begin the coding, which is fairly easy to understand!


    Step 5: Setting Up the Classes

    Go to your Flash file’s properties and name the document class MenuAccordion. Now create a new ActionScript 3.0 file and put the following code in it and save the file as MenuAccordion:

    
    
    package {
    	import flash.display.MovieClip;
    	import flash.events.Event;
    
    	public class MenuAccordion extends MovieClip {
    		public var menuAccordionMC:MenuAccordionMC = new MenuAccordionMC();
    		public function MenuAccordion() {
    			addChild(menuAccordionMC);
    		}
    	}
    }
    

    Here, we first import what we will need (in this case just the MovieClip and Event classes). Next we add the variable for our menuAccordionMC, then in the constructor we attach the MovieClip to the stage at (0,0).

    That is all the code we will need for the document class; now let’s create a new ActionScript 3.0 file for the MovieClip and save it as MenuAccordionMC.as.

    To set up the MenuAccordionMC class, input the following code – I will explain the variables and event listeners shortly:

    
    
    package{
    	import flash.display.MovieClip;
    	import flash.events.Event;
    	import flash.events.MouseEvent;
    
    	public class MenuAccordionMC extends MovieClip{
    		public var activeColor:String = new String();
    		public var speed:Number = new Number();
    
    		public function MenuAccordionMC(){
    			activeColor = "none";
    			speed = 10;
    
    			addEventListener(MouseEvent.CLICK, accordionClick);
    			addEventListener(Event.ENTER_FRAME, accordionMove);
    		}
    	}
    }
    

    First thing to notice is that we have imported the MouseEvent: this is very important because without it our mouse click will have no effect. As for the two new variables: activeColor is just a simple string to tell us which color is currently in use, and speed is how many pixels the backgrounds shift every frame.

    The first event listener is for a MouseEvent.CLICK and will call the function accordionClick when our menu is clicked anywhere. The second event listener adds the function accordionMove and will be called every frame.

    Now we will create the two functions for the event listeners. Place the following code right after the closing curly brace for the constructor.

    
    
    public function accordionClick(event:MouseEvent):void {
    
    }
    public function accordionMove(event:Event):void {
    
    }
    

    The two classes are now set up, so it’s time to start putting code in these functions!


    Step 6: The accordionClick Function

    This function is relatively easy and only has an if, else statement in it. Begin by writing the following in the function:

    
    
    if(event.target.currentFrame==1){
    
    }else{
    
    }
    

    Many people are unfamiliar with event.target, so I will briefly explain it. In a nutshell, it just directs the code to the target of the the event – so if the blueBar is clicked, event.target is equal to blueBar.

    This means that the if statement checks to see whether the bar’s currentFrame is equal to 1, and if so it executes that code; if not, it will execute the code in the second curly brackets. We can continue now and change the if, else statement to the following:

    
    
    if(event.target.currentFrame==1){
    	event.target.gotoAndStop(2);
    	activeColor = event.target.name;
    }else{
    	event.target.gotoAndStop(1);
    	activeColor = "none";
    }
    

    The new lines are very basic: the target’s currentFrame is changed to the second or first frame and the activeColor variable is set to the target’s name or it is set to “none”. That is all the code needed for the accordionClick function.


    Step 7: The accordionMove Function

    Alright, this is where all the magic happens! This is the endgame and its a long stretch to the finish, but if you follow the final instructions correctly you will have a working accordion menu!

    First thing we need to add to the function is a switch case, which will eventually include all of the if statements required for this to run smoothly:

    
    
    switch (activeColor){
    	case "none":
    
    	break;
    	case "goldBar":
    
    	break;
    	case "blueBar":
    
    	break;
    	case "greenBar":
    
    	break;
    	case "redBar":
    
    	break;
    }
    

    This switch case corresponds to the variable activeColor that is set during the accordionClick function. Now let’s start with the easiest part of this case statement, case: none:

    
    
    if(this.goldBackground.x>=-530){
    	this.goldBackground.x-=speed;
    }
    if(this.blueBackground.x>=-500){
    	this.blueBackground.x-=speed;
    }
    if(this.greenBackground.x>=-470){
    	this.greenBackground.x-=speed;
    }
    if(this.redBackground.x>=-440){
    	this.redBackground.x-=speed;
    }
    if(this.blueBar.x>30){
    	this.blueBar.x-=speed;
    }
    if(this.greenBar.x>60){
    	this.greenBar.x-=speed;
    }
    if(this.redBar.x>90){
    	this.redBar.x-=speed;
    }
    

    (Editor’s Note: You may argue that this code is not neat enough for practical use. See the comments of the other tutorial in this series for a discussion about this!)

    All that the none case does is check whether any of the MovieClips’ x-positions are greater than their original ones, if they are it moves them left until they no longer are greater than their original x positions.

    The next case, goldBar, does something similar. It moves all the other bars that are on the right side of it to the right side of the stage and the backgrounds to the bars’ previous x-positions. Then it just switches all the other bars’ currentFrame properties to 1 (so that the arrows point in the opposite direction):

    
    
    if(this.goldBackground.x<0){
    	//Moves The Bars & Backgrounds
    	this.goldBackground.x+=speed;
    
    	if(this.blueBar.x<560){
    		this.blueBar.x+=speed;
    	}
    	if(this.blueBackground.x<30){
    		this.blueBackground.x+=speed;
    	}
    	if(this.greenBar.x<590){
    		this.greenBar.x+=speed;
    	}
    	if(this.greenBackground.x<60){
    		this.greenBackground.x+=speed;
    	}
    	if(this.redBar.x<620){
    		this.redBar.x+=speed;
    	}
    	if(this.redBackground.x<90){
    		this.redBackground.x+=speed;
    	}
    	//Checks if any other bar's currentFrame is 2, if it is it switches it to 1
    	if(this.blueBar.currentFrame==2){
    		this.blueBar.gotoAndStop(1);
    	}else if(this.greenBar.currentFrame==2){
    		this.greenBar.gotoAndStop(1);
    	}else if(this.redBar.currentFrame==2){
    		this.redBar.gotoAndStop(1);
    	}
    }
    

    All right, we have two out of the five cases complete. The next three cases work the same as the goldBar – with one exception. They move any backgrounds that are open to the left of them back to their original position and shift themselves back to their original position.

    Here is the blueBar case:

    
    
    if(this.blueBackground.x<30){
    	this.blueBackground.x+=speed;
    	if(this.greenBar.x<590){
    		this.greenBar.x+=speed;
    	}
    	if(this.greenBackground.x<60){
    		this.greenBackground.x+=speed;
    	}
    	if(this.redBar.x<620){
    		this.redBar.x+=speed;
    	}
    	if(this.redBackground.x<90){
    		this.redBackground.x+=speed;
    	}
    	if(this.goldBar.currentFrame==2){
    		this.goldBar.gotoAndStop(1);
    	}else if(this.greenBar.currentFrame==2){
    		this.greenBar.gotoAndStop(1);
    	}else if(this.redBar.currentFrame==2){
    		this.redBar.gotoAndStop(1);
    	}
    }
    if(this.blueBar.x>30){
    	this.blueBar.x-=speed;
    	if(this.goldBackground.x>-530){
    		this.goldBackground.x-=speed;
    	}
    	if(this.greenBar.x<590){
    		this.greenBar.x+=speed;
    	}
    	if(this.greenBackground.x<60){
    		this.greenBackground.x+=speed;
    	}
    	if(this.redBar.x<620){
    		this.redBar.x+=speed;
    	}
    	if(this.redBackground.x<90){
    		this.redBackground.x+=speed;
    	}
    	if(this.goldBar.currentFrame==2){
    		this.goldBar.gotoAndStop(1);
    	}else if(this.greenBar.currentFrame==2){
    		this.greenBar.gotoAndStop(1);
    	}else if(this.redBar.currentFrame==2){
    		this.redBar.gotoAndStop(1);
    	}
    }
    

    The only thing new about this case is the second main if statement; this is for when another background was already open, it performs a check to see which one and then it moves it back just like the “none” case, then it changes the frames on the other bar MovieClips.

    The final two cases work in exactly the same way; the only difference between the three of these is the positions where each bar is being moved to and where its background is being moved to.

    Here are the final two cases:

    
    
    if(this.greenBackground.x<60){
    	this.greenBackground.x+=speed;
    	if(this.redBar.x<620){
    		this.redBar.x+=speed;
    	}
    	if(this.redBackground.x<90){
    		this.redBackground.x+=speed;
    	}
    	if(this.goldBar.currentFrame==2){
    		this.goldBar.gotoAndStop(1);
    	}else if(this.blueBar.currentFrame==2){
    		this.blueBar.gotoAndStop(1);
    	}else if(this.redBar.currentFrame==2){
    		this.redBar.gotoAndStop(1);
    	}
    }
    if(this.greenBar.x>60){
    	this.greenBar.x-=speed;
    	if(this.goldBackground.x>-530){
    		this.goldBackground.x-=speed;
    	}
    	if(this.blueBar.x>30){
    		this.blueBar.x-=speed;
    	}
    	if(this.blueBackground.x>=-500){
    		this.blueBackground.x-=speed;
    	}
    	if(this.redBar.x<620){
    		this.redBar.x+=speed;
    	}
    	if(this.redBackground.x<90){
    		this.redBackground.x+=speed;
    	}
    	if(this.goldBar.currentFrame==2){
    	this.goldBar.gotoAndStop(1);
    	}else if(this.blueBar.currentFrame==2){
    		this.blueBar.gotoAndStop(1);
    	}else if(this.redBar.currentFrame==2){
    		this.redBar.gotoAndStop(1);
    	}
    }
    
    
    
    if(this.redBackground.x<90){
    	this.redBackground.x+=speed;
    	if(this.goldBar.currentFrame==2){
    		this.goldBar.gotoAndStop(1);
    	}else if(this.blueBar.currentFrame==2){
    		this.blueBar.gotoAndStop(1);
    	}else if(this.greenBar.currentFrame==2){
    		this.greenBar.gotoAndStop(1);
    	}
    }
    if(this.redBar.x>90){
    	this.redBar.x-=speed;
    	if(this.goldBackground.x>-530){
    		this.goldBackground.x-=speed;
    	}
    	if(this.blueBar.x>30){
    		this.blueBar.x-=speed;
    	}
    	if(this.blueBackground.x>=-500){
    		this.blueBackground.x-=speed;
    	}
    	if(this.greenBar.x>60){
    		this.greenBar.x-=speed;
    	}
    	if(this.greenBackground.x>=-470){
    		this.greenBackground.x-=speed;
    	}
    	if(this.goldBar.currentFrame==2){
    		this.goldBar.gotoAndStop(1);
    	}else if(this.blueBar.currentFrame==2){
    		this.blueBar.gotoAndStop(1);
    	}else if(this.greenBar.currentFrame==2){
    		this.greenBar.gotoAndStop(1);
    	}
    }
    

    And with that all of the coding is complete for the accordion!


    Conclusion

    Right now you should be admiring your hard work and its magnificent result, but if you are wondering how to take the accordion to the next level and add more bars, then just remember the following:

    • The backgrounds are the size of the stage minus the total width of all the bars – which in turn is the number of bars that there are multiplied by the width of one bar.
    • Each clause of the switch case either moves all the bars and their backgrounds that are on the selected bar’s right to the right, or moves the selected bar left with the bars to its left and their backgrounds, revealing its own background

    Thank you for taking the time to read this article, I hoped you enjoyed it!


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