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

 

senocular.com ActionScript Library

snapToGrid.as

Name: snapToGrid() Snaps movieclip to a grid spacing
Author: senocular: www.senocular.com
Date: 1899-12-31T00:38:41.200
Documentation:
MovieClip SNAPTOGRID: snaps a movieclip's position grid spacing
with optional offset
 
Arguments:
- xspan, yspan: grid spacing; distance from one snap to the next.
- xgridRef, ygridRef: (optional) reference location for which the grid is to be based on
all spans are based on this point location in the grid.  Defualt: 0,0.

Update:
- removed offsets (seemed to confuse ppl) and made it so it snaps in negative locations.

Example:
// snaps mouse following movieclip to a 10x10 grid
onClipEvent(mouseMove){
	_x = _parent._xmouse;
	_y = _parent._ymouse;
	this.snapToGrid(10, 10);
	updateAfterEvent();
}

1
2
3
4
MovieClip.prototype.snapToGrid = function(xspan, yspan, xgridRef, ygridRef){
	this._x = Math.round((this._x+xgridRef)/xspan)*xspan-xgridRef;
	this._y = Math.round((this._y+ygridRef)/yspan)*yspan-ygridRef;
}