For quite some time now, I’ve been trying to figure out the best way to get lines to “move” in AS3. By this, I don’t mean simple rotation and skewing of an existing line, but actually changing the line structure: length, thickness, etc. The challenge first became noteworthy when I was working on my Tower Defense code, and I wanted to have a laser-esque tower that would shoot constantly at an enemy rather than launching projectiles. In other words, I wanted the origin point of my segment to be stationary while the other end of the segment follows the targeted creep. Based on some old Java graphics experience I have, my first thought was to re-render (literally create and destroy) the Sprite object housing the laser on a timer or Event.ENTER_FRAME. However, this immediately proved to be a poor decision, since it caused a horrible flicker, just like a Java applet that was animating without double buffering. So, needless to say, I needed to dig a little deeper into the core of the AS3 Graphics object.
Believe it or not, after Googling for what seemed like hours, I couldn’t find anything that addressed this specific question. Perhaps it was because it was too simple a solution for someone to take the time to do a write-up about, or perhaps I simply could not figure out the precise keyword phrase for which to search. Either way, I found myself reading through the Adobe Livedocs API for the Flash.display.graphics object. Since I had only been using the graphics object to draw single instances of elements to the UI in the past, I had never really had to look at the API, but I very quickly found the clear() method of this object that allows us to clear the vectors and reset all the fill values without having to destroy the object completely.
Voila! As simple as that, my solution was found. By avoiding the overhead of having to destroy and recreate the objects themselves, I could simply tell each object to clear their vectors and redraw the line with the correct coordinates. The required time is so negligible that, even at higher frame rates (my samples are all developed at 31fps), there is no flicker.
In order to really demonstrate the concept, I drew up a quick and dirty shape creator application that defaults to three conjoined points that act as handles. Each of these points may be clicked and dragged, and the lines will follow. For a little added fun, there is both a green and red button in the toolbar that add or remove additional points on the line segments. I have set a hard minimum and maximum of 3 and 8 points respectively for this demo, but I have tested with up to 20 points redrawn with no flicker to the lines at all.
You may also view the full source code.
I swear I’m not stalking you or something… Haha.
http://img532.imageshack.us/img532/4912/points.png