mattlundstrom
8/7/2013 - 6:01 PM

Utility to aid in the timing of animations. The first tap of the spacebar begins recording, and subsequent taps will have their time recorde

Utility to aid in the timing of animations. The first tap of the spacebar begins recording, and subsequent taps will have their time recorded. Tap return when done. The code maps all events to a 0-1 timeline, so it can be scaled to any duration after the fact, and traces out those values.

import flash.events.KeyboardEvent;
import flash.utils.Timer;

var beginTime:Date;
var elapsedTime:Number;
var begun:Boolean = false;
var times:Array = [];
var mappedTimes:Array = [];
var scaleValue:Number;

init();

function init()
{
  stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDownHandler);
}

function onKeyDownHandler(e:KeyboardEvent):void
{
	if (!begun)
	{
		beginTime = new Date();
		begun = true;
	}
	
	elapsedTime = (new Date().time - beginTime.time)/1000;

	switch(e.keyCode)
	{
		case 32://SPACE (MARK);
			markTime(elapsedTime)
		break;
		case 13://RETURN (DONE)
			scaleTimes();
		break;
	}
}

function markTime(seconds:Number):void
{
	times.push(seconds);
	trace(seconds);
}

function scaleTimes():void
{
	var maxValue:Number = Math.max.apply(null, times);
	var minValue:Number = Math.min.apply(null, times);
	
	for (var i:int = 0; i<times.length; i++)
	{
		var mappedValue:Number = map(times[i],minValue,maxValue,0,1);
		mappedTimes.push( mappedValue );
	}
	trace(mappedTimes);
}

function map(v:Number, a:Number, b:Number, x:Number = 0, y:Number = 1):Number {
    return (v == a) ? x : (v - a) * (y - x) / (b - a) + x;
}