Monthly Archives: September 2006

More Fun with Flash 9 Particle Systems

Back in May, I spent some time experimenting with particle systems in Flash 9 and Actionscript 3. Thankfully, I found some time to come back to this project. I had one goal in mind: The concept of a particle system must be as flexible as possible. It could be anything from the flames and steam I created in my previous project to falling snow or even something more complex that involves artificial intelligence and flocking behaviors.

Let’s take a look at a couple of the different particle systems that I’ve created. You can see that flames made a comeback in the example below. To mix things up, I used several active particle systems at once, and I threw in a video game sprite to add some flavor. It may be a little heavy on the CPU, but as you can see, a particle system (or six, in this case) can add a lot of atmosphere to a scene.

Preview image of flames particle effect

Next, I created a fountain of spraying water. The water fades from blue to white and an occasional drop flies high above the others. You’ll see that the individual particles are a little more obvious in this example, but I think I was able to give the water some personality to make up for it.

Preview image of a fountain particle effect

Finally, I wanted to create a system that featured “skinned” particles. The snowstorm that I linked to above inspired me to create an example with falling leaves. I imported vector art from Flash to represent each particle, and as you move your mouse left and right, you control the direction of the wind. I created the illusion of depth by making smaller leaves fall slower to make them appear further away from the viewer.

Preview image of a flying leaves particle effect

Not quite as impressive, though technically interesting, I also made a swarming effect using animation along Bezier curves, and I started work on a simple bitmap particle system. I’d like to spend some more time on this project because I’ve got a bunch of cool ideas, but I have to move on to other things for now. Expect me to post random cool effects from time to time.

Full source code is available under an MIT license, and I’ve included ASDoc documentation. If you decide to play around with the code at all, I’d love to see what you create!

Update (08/06/2008): For completeness sake, I’ve included two classes below, ColorUtil and PointUtil, that I reference in the examples, but I omitted from the download:

ColorUtil.as

////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007 Josh Tynjala
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to
//  deal in the Software without restriction, including without limitation the
//  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
//  sell copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
//  IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////

package zeuslabs.utils
{
	public class ColorUtil
	{
		public static function blendColors(color1:Number, color2:Number, percent:Number = 0.5):Number
		{
			var remaining:Number = 1 - percent;

			var color1RGB:Object = ColorUtil.hexToRgb(color1);
			color1 = ColorUtil.rgbToHex(color1RGB.red * percent, color1RGB.green * percent, color1RGB.blue * percent);

			var color2RGB:Object = ColorUtil.hexToRgb(color2);
			color2 = ColorUtil.rgbToHex(color2RGB.red * remaining, color2RGB.green * remaining, color2RGB.blue * remaining);

			return color1 + color2;
		}

		public static function hexToRgb(color:Number):Object
		{
			var rgbColor:Object = {};
			rgbColor.red = (color & 0xff0000) >> 16;
			rgbColor.green = (color & 0x00ff00) >> 8;
			rgbColor.blue = color & 0x0000ff;
			return rgbColor;
		}

		public static function rgbToHex(red:uint, green:uint, blue:uint):Number
		{
			return (red 

PointUtil.as

////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007 Josh Tynjala
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to
//  deal in the Software without restriction, including without limitation the
//  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
//  sell copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
//  IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////

package zeuslabs.utils
{
	import flash.geom.Point;

	public class PointUtil
	{
		public static function reverse(v:Point):Point
		{
			return new Point(-v.x, -v.y);
		}

		public static function scalarMultiply(v:Point, s:Number):Point
		{
			return new Point(v.x * s, v.y * s);
		}

		public static function scalarDivide(v:Point, s:Number):Point
		{
			return new Point(v.x / s, v.y / s);
		}

		public static function dotProduct(u:Point, v:Point):Number
		{
			return (u.x * v.x) + (u.y * v.y);
		}

		public static function rotate(u:Point, angleRadians:Number):Point
		{
			var v:Point = new Point();
			v.x = u.x * Math.cos(angleRadians) + u.y * Math.sin(angleRadians);
			v.y = -u.x * Math.sin(angleRadians) + u.y * Math.cos(angleRadians);
			return v;
		}

		public static function rotateToPoint(origin:Point, target:Point):Number
		{
			var dx:Number = target.x - origin.x;
			var dy:Number = target.y - origin.y;
			return Math.atan2(dy, dx) * 180 / Math.PI;
		}

		public static function distance(p1:Point, p2:Point):Number
		{
			var dx:Number = p2.x - p1.x;
			var dy:Number = p2.y - p1.y;
			return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
		}
	}
}

Object-Oriented Actionscript for Flash 8 overflows with knowledge (Part 2)

If you’re looking for the ultimate book on Actionscript 2 programming, Object-Oriented Actionscript for Flash 8 should be your first choice. The book comes in at 540 pages, and holds so much knowledge that I needed to break my review into two parts. Before leaping into my thoughts on the second half, don’t forget to take a look at my previous examination.

In the second half, Peter Elst and Todd Yard take a quick look at the MX Components Framework that comes with Flash, and they use the knowledge from the first part of the book to build their own framework. Chapter 14 outlines the core classes of the MX Framework, specifically MovieClip (from the native Flash classes), UIObject, UIComponent and View. This chapter mainly offers an introduction to the idea of a framework, and you’ll later discover that the authors take some ideas from these base classes to use in their own design choices.

Elst and Yard start implementing some sound and style management classes in the next chapter. The goals for this framework aren’t quite as generic as say, Adobe’s Flex Framework, so the StyleFormat utility class that goes with StyleManager has some specific properties for things like borders, shadows, and fonts. Since these properties might not apply to every component, I don’t think I’d build it like that for my own projects. However, I think that it works well as a teaching aid to help the reader visualize the purpose of the class easier. Of course, I remember a post from Jesse Warden where he considered the need for a super-flexible framework for Flash projects with ultra-short deadlines. Ideally, such a framework would exist to solve common problems, but it would need to be enormously customizable to accomodate designers. For a project like that, simple design parameters like the ones used in the example might be a good way to speed up development.

Chapter 16 lays the groundwork for user interface components. Like Flash’s MX Framework, a UIObject class provides a common interface for use with all visual components. On the next layer, the authors implement a Block class which can be used with graphical assets. For instance, one Block might be used to skin a button component. Finally, they hope to finish up with a SimpleButton component. This chapter is one of the largest in the book and it contains a good deal of information, including integration with styles, graphics, events, states, and sounds. If you’re planning on creating reusable components, I recommend studying this section a bit to help yourself understand their methods. Even if you don’t use their base classes, the process of component development should be beneficial. It’s quite common in the Flash world to build your own components from scratch. Over the lifetime of Flash, many have developers have discovered that no magic bullet exists in this area. You have to balance flexibility, file size, performance, and more.

With a component system in place, the authors dive into animations. I found this chapter very interesting because it included many examples of using inheritance versus composition. With inheritance, a subclass takes the properties and methods from its parent class. For example, a Volkswagon “is a” Car. On the other hand, composition means that a class contains an instance of another class. A Car “has a(n)” Engine. We start out by creating a base Animator class. Two more classes, Tweener and Mover inherit from Animator. Mover, interestingly enough, uses a Tweener to handle its animation. From an OOP perspective, this design re-enforces the concept of encapsulation covered in earlier chapters, and you might not even notice that it’s happening.

In Chapter 18, “Interrelationships and Interactions Between Components”, the authors look into data binding, formatting, and validating. Unlike previous chapters, where they developed their own framework solutions from scratch, they’re now using some of the classes that come with Flash out of the box. This sort of confused me a bit. It took me a little while to realize that they had finished with the framework development, and they had moved on to the section about “Data Integration”. The section also includes browser interaction through Flash’s ExternalInterface and interaction with the server through XML and web services. It’s all very useful information that every Flash developer should know about, but I feel like this section would fit better in a more general Flash book. The rest of the book has been about learning good OOP design skills. Certainly, a good skill is knowing that you shouldn’t reinvent the wheel, but I felt like the natural progression broke during the transition to this section.

The book finally reaches its end with another case study. This time, the authors build a timesheet application. You’ll see a little UML again as the authors design the class structure. They’ll make use of the Model-View-Controller design pattern again. It’s a pretty complex little project, and you’ll want to study it, and probably recreate it in Flash to understand it well. You should pick up some good nuggets of information, and its always useful to see how others develop their projects.

I’ll admit, my love for the second half isn’t as strong as the first, but that’s a little more about the presentation style than the actual content. Whatever your skill level, I believe you’ll find some great information in Object-Oriented Actionscript for Flash 8. If you’re a Flash beginner, or you’re looking to move from the timeline into proper classes, you should have bought the book yesterday. Seriously, you won’t find a better text to help you with your transition. If you’re more advanced, you’ll find that this book is an enjoyable read that might give you some new ideas. I’ve added it to my official recommendations. As a final note, don’t let it discourage you that Actionscript 3 and Flash 9 projects might be around the corner. Focus on the object-oriented parts because it doesn’t matter what langauge you use. Good design is universal.

Object-Oriented Actionscript for Flash 8 overflows with knowledge

When I picked up Object-Oriented Actionscript for Flash 8, I kept my expectations neutral. I’ve said it before, but it’s important to note, I hate programming books. They’re either too dry or too basic. Thankfully, Peter Elst and Todd Yard kept things interesting in early chapters, and their writing flowed smoothly to help keep me interested as they added on each new layer of information. Coming in at 540 pages, this mighty tome is one of the thickest Flash books on my bookshelf. I don’t own the printed version of the Actionscript 2 Language Reference myself, but it might be the only one that’s bigger.

The first chapter, “Introduction to OOP“, contains the best explanation of objects and classes that I’ve heard yet. If you’re thinking that it’s time to move on from timeline code to classes, this chapter alone should help the most in getting you started. The writers keep it short and sweet, yet these eight pages contain many great diagrams and analogies to ease you into core concepts including encapsulation, inheritance, and polymorphism. It’s so simple to visualize things like a blueprint (class) being used to create a house (object), or the fact that cars from two different companies, such as Volkswagen and Toyota, can both be started by turning a key (inheritance and interfaces). To keep the reader in a programming mindset, a few lines of pseudo-code help to reinforce each new concept.

In the next couple of chapters, the authors introduce basic programming concepts and the Actionscript 2 language. This section goes by very quickly, and if you’re just getting started, you might want to read it over a couple of times. It seems to me that the authors pretty much assume that you’ve already done a bit of programming and you’re really looking to move on to the next. If you’re coming from a different language, like Java, it’s perfect because you can easily skim to each example of syntax. I like that a lot. Everytime I pick up a book to learn a new language, I hate reading through half a dozen chapters that assume that I’ve never heard of a compiler or a variable.

Chapter 4 presents ways to plan a programming project. The reader learns about different projects phases and how to use UML to represent classes and their relationships. Chapter 5 introduces workflow tools like version control systems (like CVS or Subversion), programming appearches like RAD and Extreme Programming, and a short section on usability. The final chapter in this section goes over some of the authors’ personal best practices. They present different ways to format code, reasons for using comments, and good naming schemes for variables and functions.

With the basics out of the way, the authors begin showing real Actionscript examples of those core programming concepts covered in the first chapter. We start out with some basic encapsulation that seperates different actions into functions. As the first bit of real code, the example of a ball moving on the stage is represented in timeline code. Personally, I would have liked to see the authors just move straight into classes, but this example is a good way to get a beginner started and to keep things familiar for Flash users that are already used to the timeline.

With the ball now rolling (bad pun), the authors start implementing their first classes. Like functions, classes offer another way to encapsulate functionality. Additional parts of classes like constructors, member variables and methods give the reader his or her first taste of what’s in store. Again, examples with real-world objects, like cars, help illustrate how classes work. The “Mover” class at the end of this chapter brings the earlier ball example into the modern Flash world, and it lays the groundwork for additional expansion in the next couple of chapters. With Mover implemented, the authors tackle inheritance by creating a Bouncer class with specialized functionality and a Gravity class to help reinforce the idea.

A short chapter on polymorphism goes on a bit of a tangent. Elst and Yard move away from the Mover classes, and polymorphism is presented differently. First, the basics are explained using body states such as hunger, boredom, and tiredness. It’s interesting to see the idea of interfaces shown without them actually being introduced yet. That happens in the next chapter. I almost wonder if perhaps these examples should have been used earlier. The reader may consider it a nice break from the coding, or it may be confusing. I can’t accurately judge that since I’m already well versed in this concept. When interfaces are truly introduced, we jump back into the Mover project and implement IMovable, IBounceable, and IGravity. With the previous movement classes, the code changes very little to include the interfaces. I always have trouble with chapters on interfaces. I believe that many seasoned programmers don’t always know when interfaces are needed, and I wish programming books would show better use-cases. It’s not specific to this book, just something that I’d like to see in more OOP books and tutorials.

The authors near the end of the first half with their introduction to design patterns. Patterns offer great, tested solutions to programming problems. They’re like frameworks that help you build your projects quicker, and they help you and others maintain your code more easily. Personally, I’m still learning patterns, so I found this chapter especially useful. Unfortunately, if you’ve already learned a bit about common patterns used by Flash developers, such as MVC, Singletons, Decorators, and Observer, you might not pick up much addtional knowledge. I could be wrong, but I believe that Colin Moock’s Essential Actionscript 2.0 covers the exact same patterns. Many folks highly recommend that book, so if you have trouble with this section, consider picking it up to hear a different author’s perspective on the subject.

The first half draws to a close with a case study that uses all of the techniques covered in earlier chapters. The authors create an OOP-based Media Player that can load Flash SWFs, Video, and MP3 files. By combining design patterns, some of the classes created earlier, and all sorts of great new examples of classes and inheritance, the authors do a wonderful job of bringing everything full-circle. There’s a good deal of code presented in this chapter, but each section includes a specific explanation. If you’re just learning these concepts, I highly recommend running through this whole example in Flash to get it working. The best way to learn is to just jump in and do it.

In any other Actionscript book, I’d expect to have reached the end. However, Peter Elst and Todd Yard truly go the extra mile. The first half is mainly geared toward AS2 beginners, but the second half bursts with knowedge aimed at more advanced developers. Stay tuned for part two of my review on Object-Oriented Actionscript for Flash 8 where the authors create a framework and present chapters on some of Flash’s included classes and features that you may not even know about.