Friday, November 12, 2010

How to create Mac-like buttons using AS3

Today we will learn how to create Mac-like buttons - the closer you move your mouse to the button, the bigger it gets.

Here is an example:


The method - I create an Event.ENTER_FRAME function, which I can apply to my buttons or movie clips. In the example above, the registration points of the movie clips are set on the square's bottom border to achieve the effect.

Here is the commented code:

// scaleA - distance from the cursor to the button
var scaleA:Number;
// allLeft - if mouse is not inside stage (sets the button's size to initial)
var allLeft:Boolean = false;

stage.addEventListener(Event.MOUSE_LEAVE, LeaveStage);
stage.addEventListener(MouseEvent.MOUSE_MOVE, ReturnStage);

function LeaveStage(Event)
{
allLeft = true;
}
function ReturnStage(Event)
{
allLeft = false;
}
function roll(event:Event)
{
if (allLeft == 0)
{
// update scaleA - the 'distance' between mouse and button. play around with the number (150)
// for different results...
scaleA = 150-(Math.abs(event.currentTarget.x-mouseX) + Math.abs(event.currentTarget.y-mouseY));
// if the 'distance' is greater than 0, scale the button
if (scaleA > 0)
{
event.currentTarget.scaleX = event.currentTarget.scaleY = 1 + scaleA / 290;
}
// if the 'distance' is less than 0, set it to 1 (for de-glitching)
if (scaleA < 0)
{
event.currentTarget.scaleX = event.currentTarget.scaleY = 1;
}
}
// if we move our cursor out of stage - the buttons should smoothly decrease to 100% size
if (allLeft && event.currentTarget.scaleX > 1)
{
event.currentTarget.scaleX -=  0.1;
event.currentTarget.scaleY -=  0.1;
}
// if scale is less than 1, set it to 1
if (event.currentTarget.scaleX < 1)
{
event.currentTarget.scaleX = 1;
event.currentTarget.scaleY = 1;
}
}

// adding the events to buttons

s1.addEventListener(Event.ENTER_FRAME, roll);
s2.addEventListener(Event.ENTER_FRAME, roll);
s3.addEventListener(Event.ENTER_FRAME, roll);
s4.addEventListener(Event.ENTER_FRAME, roll);

Thanks for reading!

No comments:

Post a Comment