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

 

senocular.com ActionScript Library

constrainTo.as

Name: constrainTo() - keeps movieclip within a bounds object bounds or a movieclip bounds
Author: senocular: www.senocular.com
Date: 1899-12-31T00:33:40.400
Documentation:
MovieClip CONSTRAINTO: keeps a movieclip within the bounds of
a) another movieclip or b) a bounds object in the form of
an object as retrieved from the movieclip.getBounds() method

Arguments:
- cb: or 'constraint bounds', the bounds to which this movieclip is to be constrained.  This can
be either a movieclip or a getBounds object.  As a getBounds object it doesnt have to be an
object specifically from a getBounds action, but it has to be in the same format, which is an 
object containing the 4 following properties
xmin - the 'left' of the bounds, how far left this clip can go
xmax - the 'right' of the bounds, how far right this clip can go
ymin - the 'top' of the bounds, how high this clip can go
ymax - the 'bottom' of the bounds, how low this clip can go
ex:
myBounds = {xmin:0,xmax:200,ymin:10,ymax:90};
this.constrainTo(myBounds);

Example:
onClipEvent(enterFrame){
	// generic move movieclip around function 
	this.moveAboutRandomly();
	// keep clip within the box area
	this.constrainTo(_root.box);
}


1
2
3
4
5
6
7
8
MovieClip.prototype.constrainTo = function(cb){
	if (typeof cb == "movieclip") cb = cb.getBounds(this._parent);
	var tb = this.getBounds();
	if (this._x + tb.xmin < cb.xmin) this._x = cb.xmin + tb.xmax;
	else if (this._x + tb.xmax > cb.xmax) this._x = cb.xmax + tb.xmin;
	if (this._y + tb.ymin < cb.ymin) this._y = cb.ymin + tb.ymax;
	else if (this._y + tb.ymax > cb.ymax) this._y = cb.ymax + tb.ymin;	
}