Thursday, May 28, 2009

Taught myself some more Flash today.



So I wanted to figure out how to make a navigation bar in which an indicator would move in a fluid fashion toward whatever you just clicked on. This could be for a website, interactive timeline, game menu, etc. This particular example I wanted the arrow to just move to the same horizontal (x) position as the mouse at the instant of the click. I also wanted to constrain it to a range of x values, specifically, to the width of the navigation bar. So when you click anywhere to the right or left of the bar, the arrow will only travel to the bar's edge.

Just for shits I also made a dynamic text field that constantly refreshes the pointer's x position as a percentage of the width of the bar.

Here's the code:


import fl.transitions.Tween;
import fl.motion.easing.*;

trackerMC.x=navBar.x;
trackerMC.y=navBar.y;

stage.addEventListener(MouseEvent.CLICK, comeHere);

function comeHere(event:MouseEvent):void {
var xTarget:Number=mouseX;
if (xTarget>navBar.x+navBar.width) {
xTarget=navBar.x+navBar.width;
} else if (xTarget < navBar.x) {
xTarget=navBar.x;
}
//trace(xTarget);
var xTween:Tween=new Tween(trackerMC,"x",Quartic.easeOut,trackerMC.x,xTarget,1,true);
xTween.start();
}

addEventListener(Event.ENTER_FRAME, refreshXPos);

var xPos:Number;

function refreshXPos(event:Event):void
{
xPos = Math.ceil((trackerMC.x - navBar.x)/navBar.width*100);
positionTxt.text = xPos.toString();
}

2 comments:

Teresa said...

Geeky, but very good!

John Petersen said...

Actually, I should have defined my variables at the top of the code, like a good Flash programmer would do.