Use to speed up your coding

November 24th, 2009

Here’s a quick tip that will make your Flash projects a bit easier – When you have more then one object on the stage that does the same thing, ie. is draggable or activates the same event when clicked, will allow you to use a lot less code.

In this example, I’m creating two boxes on the stage, one red and one blue. I want to be able to drag both around the stage. Normally I would make a function for the red box and one for the blue box.

function dragRed(e:MouseEvent):void

function dragBlue(e:MouseEvent):void

And, of course, the functions for stopDrag().

But now I do it this way. Here’s the entire code to make the boxes and make them draggable:

var redBlock:MovieClip = new MovieClip();
var blueBlock:MovieClip = new MovieClip();,1);,50,100,100);

function moveBlock(e:MouseEvent):void

function stopBlock(e:MouseEvent):void

redBlock.addEventListener(MouseEvent.MOUSE_DOWN, moveBlock);
redBlock.addEventListener(MouseEvent.MOUSE_UP, stopBlock);
blueBlock.addEventListener(MouseEvent.MOUSE_DOWN, moveBlock);
blueBlock.addEventListener(MouseEvent.MOUSE_UP, stopBlock);

When you MOUSE_DOWN on either the redBlock or the blueBlock, Actionscript will use to make that one targeted by the function.

This will make targeting objects on the stage require a lot less coding.

Leave a Reply

Your email address will not be published. Required fields are marked *