Back in late October of last year I started up a new website called ActionSnippet.com. I created the site because I really enjoy reading code - I often skip all the paragraphs in a blog post and just go straight for the code. A new code snippet is posted daily on ActionSnippet.com, usually with a brief description.
I would have linked to ActionSnippet.com sooner but I wasn't sure what direction the site would go in, so I wanted to give it some time to evolve before linking to it. After approximately 260 code snippet posts I can safely say there is much more useful/educational code on ActionSnippet.com than there is weird useless experimental code.
In this post I'd like to highlight a handful of useful snippets for everyday projects and I'll link to a few advanced graphical snippets. If you just want to dig right in, you can look at the all posts page which is just a list of every code snippet on the site.
As you read each of the following descriptions, consider opening Flash, pasting the code into timeline script and testing the swf.
FileReference.save()
-
var file:FileReference = new FileReference();
-
stage.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
-
function onClick(evt:MouseEvent):void {
-
file.save("some text.\nsome more text", "actionsnippet.txt");
-
}
This is one of my favorite features of Flash 10. We can save any kind of file to a user's computer using the FileReference.save() method. Its first argument is for the data to put in the file. This can be a String, ByteArray, or XML object. The second argument is the name of the file.
If you paste this code in your timeline all you need to do is click the stage and you'll get a dialogue asking where you would like to save the file "actionsnippet.txt".
Quick Alphabet Array
-
var alphabet:Array = ("abcdefghijklmnopqrstuvwxyz").split("");
-
-
trace("this is the letter b...", alphabet[1]);
-
trace(alphabet);
outputs:
this is the letter b... b a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z
This snippet can be used to quickly create an array of letters. In this case we create an array out of the alphabet. The only thing you need to know to understand this snippet is the String.split() method. String.split() takes two arguments: a delimiter and a limit value. In our case we just use the delimiter argument. A more normal example of String.split() might look like this:
var names:String = "Jon, James, Jeff, Joe, Kim, Kip";
// To get all these names into an array we can use the String.split() method:
var allNames:Array = names.split(", ");
Here we have a String called names that contains six different names. The names are delineated by a comma and a space ", " so this is what we pass to the delimiter argument of the String.split() method. String.split() then returns an array where "Jon" is the first value, "James" is the second value, etc....
An interesting feature of String.split() is that if you pass an empty string as the delimiter argument, the string will get split after ever character. This is how the original snippet works. Because we don't supply a delimiter, we end up with an array filled with the alphabet.
There are many different ways to use String.split(). The limit argument could be used so that the String is only split a given number of times. String.split() can also be used with regular expressions.
As a side note, Ted from lazylady.se pointed out that this snippet could be written without parenthesis:
var alphabet:Array = "abcdefghijklmnopqrstuvwxyz".split("");
Random Choice
-
function randomChoice(...args:Array):*{
-
return args[int(Math.random()*args.length)];
-
}
-
-
// choose randomly from a number of different values
-
var val:* = randomChoice(10, "Hello", "0xFF0000", 1000);
-
-
// choose a random color (in this case red, green or blue)
-
var randColor:uint = randomChoice(0xFF0000, 0x00FF00, 0x0000FF);
-
-
trace(val);
-
trace(randColor);
The function randomChoice() takes any number of arguments and returns one of them randomly. This is useful for color values, arbitrary sets of numbers or sets of mixed datatypes. Let's take a look at how it works.
Using Math.random() to generate numbers in a given range is easy:
-
// 0 to 9
-
trace(int(Math.random()*10));
-
-
// -50 to 50
-
trace(Math.round(Math.random()*100) - 50);
But what if you only wanted Math.random() to give you one of the following numbers 10, 108, 200 or .5? One way to do this is to create an array of those values and then set a random index value based on the length of the array:
var vals:Array = [10, 108, 200, .5]; // index of vals is 0 - 3 (or the length of vals - 1) trace(vals[int(Math.random() * vals.length)]);
The above will trace out one of the values from the array vals. This works nicely, but writing a function to handle it is a bit cleaner. The randomChoice() function uses the exact same technique shown above. The key is that we make use of the AS3 ...rest parameter (...) for our Array. When used, the ...rest parameter should always be the last argument in your function because it tells Flash to allow any number of additional arguments to be passed into the function. These additional arguments will then be treated as an array. In the case of the randomChoice() function we only need to define one argument:
function randomChoice(...args):* {
The information passed into args is treated as an array and we're able to use Math.random() to grab a value from that array. Since arrays can have mixed data types, the randomChoice() function return value is typed using * (wildcard). This means it can return any datatype String, MovieClip, uint, int, Number etc... Before moving on you may consider playing around with the randomChoice() function for a few minutes.
"with" Statement and the Graphics Class
-
with(graphics) {
-
beginFill(0xFF0000);
-
drawRect(0, 0, 100, 100);
-
endFill();
-
beginFill(0xFFFF00);
-
drawRect(10, 10, 80, 80);
-
endFill();
-
beginFill(0x0000FF);
-
drawCircle(50, 50, 40);
-
}
This snippet shows how using with statements in conjunction with Graphics class method calls can save you some typing and improve code readability. We talked about this in the book on page 142-143.
A less-readable way to do this in one line looks like this:
-
// draw red circle
-
with (graphics) beginFill(0xFF0000), drawCircle(200, 100, 30);
This is often less readable than the multi-line approach so in cases with three or more method calls I'll usually choose the multi-line with statement.
Set Multiple Properties of an Object
-
var s:Sprite = new Sprite();
-
s.graphics.beginFill(0x000000);
-
s.graphics.drawRect(0, 0, 10, 10);
-
addChild(s);
-
-
// set some properties
-
setProps(s, {x:100, y:100, scaleX:2, scaleY:2, rotation:45});
-
-
// set multiple properties of an Object
-
function setProps(o:*, props:Object):void {
-
for (var key:String in props) {
-
o[key] = props[key];
-
}
-
}
This snippet allows us to set the properties of any Object using a function call and Object syntax. This technique is commonly used within tweening engines such as TweenLite.
Take a look at line 7. Here we call the setProps() function. The first argument is the Object (a Sprite, in this case) that we want to change and the next argument is an Object that contains new values for the properties of the object you passed into the first parameter. Line 7 alters our sprite's x, y, scaleX, scaleY and rotation properties all with one function call.
The setProps() function itself makes use of two interesting ActionScript features, the for...in loop and Object bracket syntax. Bracket syntax can be very powerful. It's an alternative to dot syntax, instead of writing:
mc.x = 10; mc.y = 10; mc.rotation = 45; // bracket syntax allows us to write: mc["x"] = 10; mc["y"] = 10; mc["rotation"] = 10;
The reason this is useful is that you can use a variable between in your brackets and change which property or method you're targeting.
On line 11 we make use of the for...in loop. This allows us to loop through the properties in a given Object (stored in props, in this case). Notice the key variable inside our for...in loop. This variable is set to the name of each property in our props Object. To understand this a bit better you could try adding a trace statement inside the for...in loop:
for (var key:String in props){
trace(key);
}
outputs:
scaleY y x rotation scaleX
This means that line 12 is setting the properties of our first argument equal to the properties of our second argument. If we unrolled the loop it would look like this:
o["scaleY"] = props["scaleY"]; o["x"] = props["x"]; o["y"] = props["y"]; // etc
Here are a few posts that expand on the setProps() snippet:
Instantiate and Set Properties
Object Argument w/ Defaults
Additional Useful Posts
Here are a few more snippets that I find myself using often:
Multiple Keys
Loading, Centering & Smoothing
Dynamic Vars Dictionary
Mouse Velocity
Toggle Visible
Visual Experiments
Here are a few select visual experiments from ActionSnippet:

Perlin Noise with parallax displacement.

A 3D shape created with setPixel().

A plot of a 3D Implicit surface, using the Flash Player 10 Utils3D.projectVectors() method.
Graphics Algorithms
There are a good deal of posts on ActionSnippet related to graphics algorithms. Here are a few select examples:
Quadratic Bezier Curve
Bresenham line
Bresenham Circle
Catmull-Rom Spline
There is a rather extensive post about Bezier Intersections. The demo can be seen here and the post is here.
Don't be Afraid
There are some pretty advanced snippets lurking around on ActionSnippet, but just because code looks complex doesn't mean that you shouldn't dive right in and start playing around with it—especially if it does something that you're interested in learning how to do. Don't be afraid! Copy and paste that code into your timeline and start changing some numbers around!
QuickBox2D
You'll notice that some of the more recent posts on ActionSnippet make use of a library called QuickBox2D. You can read more about the library here. I expect to post a tutorial about QuickBox2D in the near future.
Print This Post


(17 votes, average: 4.18 out of 5) 































The FileReference.save() method didn´t work to me. I´ve received the follow error:
1061: Call to a possibly undefined method save through a reference with static type flash.net:FileReference.
There is code for FileReference.save() for saving a text file. Works great!
How do I load that same text into a text field using FileReference.load() and browse()?
Hey Frank... your right... load() and browse() are the way to go.... have a look at this snippet:
var file:FileReference = new FileReference(); file.addEventListener(Event.COMPLETE, onSaved); stage.addEventListener(MouseEvent.CLICK, onSave); function onSave(evt:MouseEvent):void { file.save("some text.\nsome more text", "actionsnippet.txt"); } // user has saved the file... clicking again will bring up the browse window function onSaved(evt:Event):void{ file.removeEventListener(Event.COMPLETE, onSaved); stage.removeEventListener(MouseEvent.CLICK, onSave); stage.addEventListener(MouseEvent.CLICK, onBrowse); } // bring up the browse window in reponse to a mouse click function onBrowse(evt:MouseEvent):void{ file.browse([ new FileFilter("Text Files", "*.txt")]); file.addEventListener(Event.SELECT, onSelected); } // user has selected a file to upload from the localhost function onSelected(evt:Event):void{ stage.removeEventListener(MouseEvent.CLICK, onBrowse); file.removeEventListener(Event.SELECT, onSelected); file.load(); file.addEventListener(Event.COMPLETE, onContentLoaded); } // the local file has been loaded, trace out the data and remove the last listener function onContentLoaded(evt:Event):void{ var txtContent:String = String(evt.target.data); trace(txtContent); file.removeEventListener(Event.COMPLETE, onContentLoaded); }@Marcos This feature is flash player 10 only... that message makes me think you may be using CS3 or publishing to flash player 9