Moving a movieclip towards the mouse but stopping short
I'm experimenting with different control schemes for something I'm working on at the mo开发者_开发知识库ment and I've currently made it so that a movieclip can follow my mouse cursor. My problem is that it comes and sits right on the point of the cursor (as it's 'supposed' to). I'd like to have a radius of around 10px surrounding the cursor that the movieclip would stop at so that it heads towards the cursor but stops short. The only way I can think to do this would be with collision detection but that seems like a very clumsy route to take.
Here's my code that moves the movieclip towards the mouse:
this is run on ENTER_FRAME
var dx:Number = stage.mouseX - this.x;
var dy:Number = stage.mouseY - this.y;
this._vx = Math.cos(Math.atan2(dy, dx)) * this._speed;
this._vy = Math.sin(Math.atan2(dy, dx)) * this._speed;
this.x += this._vx;
this.y += this._vy;
Why not use Pythagoras theorem to check the distance?
var a:Number = stage.mouseX - x;
var b:Number = stage.mouseY - y;
var dist:Number = Math.sqrt(a*a + b*b);
if(dist > 10)
{
_vx = Math.cos(Math.atan2(b, a)) * _speed;
_vy = Math.sin(Math.atan2(b, a)) * _speed;
x += _vx;
y += _vy;
}
package { import com.Ball; import flash.display.Sprite; import flash.events.Event;
public class Main extends Sprite {
private var bal:Ball;
private var easing:Number=.3;
public function Main():void {
init();
}
private function init():void {
bal=new Ball(8,Math.random() * 0xffffff);
addChild(bal);
addEventListener(Event.ENTER_FRAME,animAction);
}
private function animAction(e:Event):void {
var dx:Number=mouseX - bal.x;
var dy:Number=mouseY - bal.y;
var ax:Number=dx * easing;
var ay:Number=dy * easing;
bal.x+= ax;
bal.y+= ay;
}
}
}
精彩评论