Monday, January 17, 2011

15 Useful AS3 Snippets on Snipplr.com

15 Useful AS3 Snippets on Snipplr.com:

When working with Flash and Actionscript 3.0 you may often find yourself repeating code from one project to the next. Creating your own library of reusable code snippets (on snipplr.com for example) is a great way to speed up development. Check out these 15 snippets which you may find useful for integrating into your own code library.

Some of the following snippets are presented here as functions which can simply be used as-is. While you should be able to drop these into your own code as needed, I highly recommend you take the time to really look at the code to get a deeper understanding of what is happening. Looking at code snippets is a great way to learn new techniques and improve your programming skills overall.


Introducing Snipplr.com

Snipplr is one of Envato’s most recent acquisitions. A code snippet repository, a social hub and a darn useful addition to the Envato toolbelt! With Snipplr you can keep all of your frequently used code snippets in one place, accessible from any computer. You can share your code with other visitors and make use of what they post.

Snipplr

You can follow @snipplr on Twitter and keep up to date via the new Snipplr Facebook page. If you have any of your own AS3 snippets you’d like to share, add them to Snipplr and leave the url in the comments!

Marketplace user? Why not link to your Snipplr account from your Marketplace social profile?

1. Randomize an Array

To randomize an array we loop over the length of the array, removing an object chosen at random and then adding it back onto the Array’s end position. Think of this as having a deck of cards where you pick a card at random from the deck and move it to the top of the stack repeated for the total number of cards in the deck.

It’s important to note that the splice method returns an Array containing the removed object and not the object itself hence adding the [0] after the splice call to reference the contained object.


2. Position Display Objects in a Grid Layout

This is a short way of positioning display objects in a grid layout. It makes use of the modulo operator (%) to position each display object along the x axis and the floor method of the Math class for the y position.

This example creates 20 instances of a custom display object called MyDisplayObject positioning each instance in a grid 5 columns wide. As you may have guessed, the two 5′s in the snippet represent the number of columns in the grid.


3. Remove All Children From a DisplayObjectContainer

DisplayObjectContainer, a parent class of the more common container classes such as MovieClip and Sprite, does not have a built in method to immediately remove all children. To remove all children we simply use a while loop to remove the child which occupies index 0 in the stack until no children remain.


4. Get URL of the Page Where SWF is Embedded

[...]

No comments:

Post a Comment