Tutorials, extensions, and source files for ActionScript, Flash, and other Adobe products.

 

senocular.com ActionScript Library

snap.as

Name: snap() - 'rounds' a number to the closest increment of the range in respect to the base
Author: senocular: www.senocular.com
Date: 1899-12-31T00:34:03.400
Documentation:
Number SNAP: rounds a number to the nearest increment of the
'range' in respect to the 'base'

Arguments:
- range: the difference from one 'rounded' value to the next
- base: the reference number from which the 'rounded' values are based on. If the base is
0, and the range is 10, returned values could range from ...-20, -10, 0, 10, 20, 30...

Returns:
- returns the numbers closest rounding point based on arguments.

Example:
// This will rotate a clip in 90 degree intervals based on a 
// 45 degree base, i.e. the clip will rotate to 45, 135,
//-135 and -45 continuously.
onClipEvent(enterFrame){
	rot += 5;
	_rotation = rot.snap(90,45);
}

1
2
3
4
5
6
7
8
Number.prototype.snap = function(range,base){
	var dif = (this-base) % range;
	var n = this - dif;
	if (dif > 0){
		if (dif > range/2) n += range;
	}else if (dif < -range/2) n -= range;
	return n;	
}