Google Analytics Style Graphing with AS3

Developers who have been using Google Analytics for any time can appreciate the flexibility and power behind some of the graphing software it offers. I recently found myself wondering just how they get the incredibly usable effect they have, so I began tinkering with some Actionscript and soon found myself with a very workable base that not only could be modified and grown to match what this software offers but is also surprisingly simplistic in nature.

Basically, we simply have our main application (or graph in this case) that can take any number of argument values and calculate not only their position based on ratio but also spreads them across the graph in a readable way. So, we create a simple point object that handles the visuals – both the expanding and contracting as well as the showing and hiding of the value text – and allow our graph to do some very simple calculations to spread them out evenly.
Continue reading

Harnassing the Power of Timers in AS3

Anyone who has had the experience of trying to time events for web via client side scripting before can readily appreciate the power and ease of using the robust Timer class in Actionscript 3. Similar to the idea of using JavaScript’s setTimout and/or setInterval methods, we can use this class to set a timer for a millisecond count that will simply trigger a TimerEvent when the timer has reached its end. The beauty of it, though, is that when the timer is created, we can explicitly declare how many times we want the timer to run! No more sloppy looping of intervals or timeouts: just set your timer to X number of loops and start it running.

So, obviously, if we create a timer to run once, it is the equivalent of running a setTimeout function. As with the aforementioned JavaScript functions, we set the timer with a number of milliseconds we want to wait before triggering its event. As an optional second argument, we pass in the number of cycles we wish the timer to run. Also, since the timer is an object, even if we set the timer to run only once, we can call the start method on it and manually run that single timer multiple times throughout our script. With a little creative thinking, I’m sure you can already come up with dozens of ways this could be useful.
Continue reading

Optimizing Code Reusability and Minimizing Your Footprint

One of the most common questions I am asked is also one of the biggest problems I see in code as I read it: lack of optimization. I often have people asking questions about how they can consolidate the generic actions they want multiple objects to have access to perform without duplicating the code. In Actionscript, just like any other coding language, the duplication of code is typically a red flag that you are doing something wrong. No, not wrong in the sense of broken, but wrong in the sense of best practice and code optimization. It is much easier to have one handler function to debug and keep up than to have that same handler individually executing in a dozen different class objects.

Quite possibly the single most useful thing I have discovered in optimizing some of the graphical effects I use over and over again is simply making use of the event object in my callback functions. When you attach an event listener to an object and the event is triggered, the event passed into the callback function has a target attribute that is a reference to the object which initially triggered the event. Accessing the object this way lets us generalize handlers (such as a fadeOut function) that will consolidate our code and give us uniformity in execution.
Continue reading

Consistent Omnidirectional Movement in AS3

One of my biggest gripes in Flash games to date is that of simulated motion that is by no means realistic. True, this may be acceptable for some games, but as a whole, there is something that just doesn’t feel right when your side scrolling shooter plane moves up one unit when you press UP, left one unit when you press LEFT but moves both up and left one entire unit when you have both keys depressed. Logically, by moving in two directions at once, your character or vehicle should not be granted an additional bonus to their movement speed. Not only does it offer unfair advantages to the competent player who learns to use this loophole to his advantage, but it also makes your control somewhat unwieldy. The human brain is able to estimate precise movements and predict where things should go, and some people, though they may not know the precise reasons, will gravitate to those games that their minds can accurately predict the outcome of a motion.

If you have read my last few posts, you understand that this more realistic motion has driven me to all sorts of physics and algorithmic studies in the past weeks. Today, though, I decided to write on something a bit more fun. Those of you who remember the great old days of R. C. Pro-Am, Super Off Road or other top view racing games can attest to both the challenge and creativity about learning to control a car driving in an omnidirectional world without having to sit directly behind the wheel.
Continue reading

Pendulums, Gravity and Angular Acceleration

Continuing my personal studies on simulating true gravitational acceleration in Actionscript, a couple days ago I arrived at one of the more conceptually challenging tasks I have tackled to date: the pendulum. I say conceptually challenging, because I tried to create a realistic pendulum in Flash a year or so ago and gave up after giving it a go. Now I realize that not only was my understanding of Actionscript limited then, but my realization of what true pendulum physics entails was also somewhat amiss.

As with any new task I set out to complete (especially those requiring a significant level of new knowledge on my part), I start with an array of Google searches — search terms like pendulum math, pendulum physics and actionscript pendulum tutorial to name a few. What intrigued me is that, while the results for such searches were incredibly numerous, very few of them actually tackled the topic of realistic pendulum movement. Instead, the majority of them (like this informative tutorial) create a facade to display a fairly believable pendulum motion by setting some random oscillation variables to the rotation of the movie clip. While this may suffice for the average SWF presentation, I wanted to find a much more realistic look that actually allows the pendulum object to react to forces acting upon it.
Continue reading

Simulating Gravitational Forces in AS3

So, I may have bitten off a bit more than I could chew in this post, but it is something that has been an intriguing thought to me for some time: how can I simulate the effect, or pull, of gravitational forces between different objects on my stage? Obviously, if you read my previous post, you know that I have had some fascination with orbits and circular motions, but I am much more interested in paths that appear to be natural — almost evolving, if you will.

This got me to contemplating that, in our universe, every object acts upon every other in some way: keeping our planets in orbit around the sun while helping each other to retain their individual satellites and keep from hurtling into outer space. Embodying the interactions of the various bodies on one another and trying to come up with a simple enough algorithm that will simulate a fluid motion while not overloading the Flash player with unnecessary overhead was my goal. I have some work yet to do, but I thought I would at least share my concepts with you and see what improvements can be made whilst still keeping things lightweight.
Continue reading

Circular Rotation and Orbiting in AS3

Once again, the OOP support in AS3 makes for simplifying some previously complicated effects down to a simple implementation. In this post, I want to give an overview of something that nearly anyone who ever deals in manual animation will need to figure out: circular rotation and/or orbiting around another object. To assist in this, I have created an extremely simple orbiter class that will take a few arguments to define its behavior along with a target (or origin) around which to orbit. I have written this in such a way as to accept any Object as an origin, so this will allow us to assign an Orbiter object to rotate around anything in our SWF.

Now, as many people are not only apprehensive about math when dealing in Flash but also attempt to avoid it entirely. That is one of the reasons I tried to consolidate the orbiting pattern into a simple object: it allows for us to deal with one single algorithm that can be found all over the internet and implement it to nested objects to create some pretty complex orbital patterns. Of course, since we are dealing with circular patterns, this isn’t the appropriate method to approach the issue of true planetary or elliptical orbits, but for effects and basic visuals, it works quite well. The Orbiter object is not intended to be a solution in and of itself, but rather it is intended to be a base class upon which you can build specific rotational objects with their own visuals and effects.
Continue reading

Tower Defense in AS3 – Part IV

Many of you have been waiting patiently for this post, and let me say that I have worked many hours to get this where it is today. I wanted to get my code to the point where it was solid enough that I would actually publish something with it, and I believe it is there. Thanks to those who have encouraged me to finish this post, and I look forward to seeing how it is used!

In introduction, let me say a few things about this post: first, I have tried to alter my scope slightly in order to be more accessible to readers who may not have access to a full licensed copy of Flash. So, to help with that and make these lessons more accessible, I have decided to write them in such a way as to be compiled by the Flex SDK, a fully open source framework to allow anyone to build robust Flash applications. I prefer to use the full Flex Developer 3 for development and release, but even without it, you can compile full AS3 or Flex applications using only the SDK from the command line. One other major benefit to doing my development with Flex Builder is the ability to publish my source code for all to view online as well as download.

Obviously, this opens up the accessibility to a much broader range of individuals looking to learn Actionscript 3 or Flex. So, all this to say that the code in this post, while doing practically the same thing as the previous posts (and keeping the majority of the same logic), cleans up a ton of structural issues to lend itself more cleanly towards a completed project. That being said, we are simply focusing on the Tower object itself this time. I will leave it to your imagination and time to read through the rest of the cleaned – and fully documented, I might add – code. I may find time to write some more generalized posts on the Flex framework itself in days to come, but for now, suffice to say that the main file that is compiled as the application (in our case, called “MagicTD.as”) will be instantiated as the main() function and will serve as our entire platform base. You will notice on line 12 of this file all the variables needed to set up our SWF with the desired dimensions, background color and framerate.

So, without further ado, let’s jump right into our Tower class.
Continue reading

Tower Defense in AS3 – Part III

I decided to take a slightly different approach to Phase III of this series than I had initially intended, since there was a little restructuring that needed to be done in order to support a cleaner and more efficient system. The intent was to have this post cover the basic solution to the towers themselves, but after getting back into the code, it made more sense to discuss stage structure, wave management and creep variety first. This way, we will actually have something on which to test our towers when we make them.

When you finish reading this post, you will have the ability to customize your waves via an XML file along with defining the path of the road — and therefore the creeps — in the same XML document. Allowing for customization in this way will pave the way for building a framework that can be enhanced for many different uses.
Continue reading

Movement and Event Handling with AS3

Target Practice in AS3

A couple days ago, I decided I wanted to teach myself a few movement algorithms withing Flash using Actionscript 3. I started with simple Event.ENTER_FRAME event trapping to move an object across the screen, and then I decided to make it a bit more interesting. What I ended up with is this small target practice game. It isn’t very feature rich by any means, but the different things I was able to learn and apply in a relatively short amount of time — like my particle system, easing an object into a destination and MouseEvent trapping — are invaluable to learn if you are going to do anything remotely professional with AS3.

Although I don’t claim to be a professional yet (that will come with time), my intent is to share any interesting discoveries I have made in order to help someone along through the learning stages I have just completed. Just below this paragraph, you will see the target practice game displayed. Simply click the targets to destroy them, and when you need more (or if you want to overload the app), just click the green circle in the top right. You will notice that a main feature of this app is significant randomization: from the position and motion of the targets to the amount and direction of the debris that scatters when those targets are destroyed. So, to aid in your learning, I have provided the source code for this app for you to study as well. The download link will appear at the end of the post.
Continue reading