Control a Timeline with Mouse Position

Stage.width

From now on, just about every time you work with actionScript you'll set a variable equal to the width of the stage. But instead of looking it up and setting a simple variable (like sW = 500;) we're going to have Flash look it up the stage width for us. This is incredibly handy, especially if you change the width of your stage, because you won't have to change your variable. Flash automatically updates for you!

  1. Click Statements > Variables > var
  2. In the Variables box type sW = Stage.width
  3. Select Number from the Type drop-down-list

You can trace (sW); to make certain it's working, but we're going to use it right now so hold off on that.

The plan is to turn the x position of the mouse into a percentage of the stage width. Confused? When _xmouse is at 0, the mouse has traveled 0% across the screen. When _xmouse is all the way at the right edge of the stage, the mouse has traveled 100% across the screen (and since we're having Flash fetch the Stage.width for us, it won't matter how wide the stage is).

This should be easy. We calculate the percentage by dividing the small number (the _xmouse position) by the big number (the stage width). Modify the xPos variable:

Ok, test your work and check the Output window for numbers from about 0 to 1 as you pass the mouse cursor from left to right:

Ok, now let's convert to a percentage by multiplying by 100 (that sixth grade math class is finally coming handy):

Ok, if you test now you'll see we're just about there. We want to pass the mouse over the stage and have a clip play from 1 to 100 frames. The problem is that we have a TON of decimals, but frames are only represented as whole numbers (there is no frame 30.2983984) so we need to do some rounding.

Fortunately, Flash has built-in rounding capability: Math.round

It's simple, start with Math.round, then enclose the number you want to round in parenthesis: