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

 

senocular.com ActionScript Library

avoidMouse.as

Name: avoidMouse() - move movieclip to avoid mouse
Author: senocular: www.senocular.com
Date: 1899-12-31T00:12:05.700
Documentation:
MovieClip AVOIDMOUSE: Moves a movieclip to avoid the mouse as
it approaches

Arguments:
- distance: distance at which the mouse is close enough for the movieclip to react and
begin to move away.
- speed: the speed at which the movieclip moves away from the mouse
- accel: (optional): if used, represents an 'acceleration' of the clip away from the mouse.
When accel is given, speed defaults to a maximum speed.  If at any point distance surpassed
accel and speed is 0 and the clip will abruptly stop.

Example:
onClipEvent(enterFrame){
	this.avoidMouse(100, 10);
}

1
2
3
4
5
6
7
8
9
10
11
MovieClip.prototype.avoidMouse = function(distance, speed, accel){
	var xdiff = this._parent._xmouse - this._x;
	var ydiff = this._parent._ymouse - this._y;
	var dist = Math.sqrt(xdiff*xdiff + ydiff*ydiff);
	if (dist < distance){
		var angle = Math.atan2(ydiff, xdiff);
		if (accel) speed = Math.min(speed, accel*distance/dist);
		this._x -= Math.cos(angle)*speed;
		this._y -= Math.sin(angle)*speed;
	}
}