venerdì, gennaio 16, 2009

8 AS3 Snippets

I was going to create a “top 10” list for 2008, but I’d like to make sure I remember to post this…so here are 8 snippets of simple ActionScript 3 code – nothing earth-shattering (especially to an expert), but items I find myself looking up all the time.

 

1.       Disable/enable a button component

myButton.enabled = true;

 

2.       Creating a mask
mc1.mask = mc2;

 

3.       Create a rounded rectangle

// http://www.kirupa.com/forum/showthread.php?p=1878656

var square:Sprite = new Sprite();

square.graphics.beginFill(0xFF);

square.graphics.drawRoundRect(0, 0, 100, 50, 10, 10);

square.graphics.endFill();

addChild(square);

 

4.       Custom cursor

// http://www.eclips3media.com/workshop/2007/12/11/custom-cursor-bug-in-actionscript3/

var hoverMagnify:mcMagnify = new mcMagnify();

hoverMagnify.mouseEnabled = false;

addChild(hoverMagnify)

function mouseMoveHandler(evt:MouseEvent):void {

                // whenever the mouse moves, place the cursor in the same spot

                hoverMagnify.x = mouseX + 1;

                hoverMagnify.y = mouseY + 1;

}

 

5.       Add a sound, and control its volume
var soundBg:Sound = new audioWinterWonderland();

var sc:SoundChannel = soundBg.play(0,999999); // repeat sound 999,999 times

var st:SoundTransform = sc.soundTransform;

st.volume = 1; // set to full volume

 

function changeVolume(): void {

Tweener.addTween(st, {volume:.1, onUpdate:updateChannel, time:1});

}

function updateChannel():void{

                sc.soundTransform = st;

}

 

6.       Loading an asset from a SWF

 [Embed(source="Assets.swf", symbol="MySymbol")]  

var mcClass:Class;

var myMC:MovieClip = new mcClass();

addChild(myMC);

// Note: Per this great blog entry, the default type will be a sprite unless there are two frames on the timeline.

 

7.       Create a timer

var timer:Timer = new Timer(1000, 2);

    timer.addEventListener(TimerEvent.TIMER, blah);

    timer.start();

 

function blah(e:TimerEvent):void{

     trace("Times Fired: " + e.currentTarget.currentCount);

     trace("Time Delayed: " + e.currentTarget.delay);

}

 

8.       Detect if one movieclip is over another

//As the D-mode blog nicely explains:

myMC1.hitTestObject(myMC2);

1 Comments:

Anonymous Anonimo said...

@ #7, It's useful to note what the parameters mean. Timer(1000, 1). Peter deHaan has a great article entitled "Using the Timer class in ActionScript 3.0."
The first parameter controls how frequently the TimerEvent.TIMER event gets dispatched (in milliseconds). The second parameter is the number of times that the TimerEvent.TIMER event will be dispatched before stopping. In this example, the timer will dispatch only once before quitting.
http://blogs.adobe.com/pdehaan/2006/07/using_the_timer_class_in_actio.html

2/05/2009 4:18 PM  

Posta un commento

<< Home