此代码使用距离公式Math.sqrt((x1 – x2)^ 2(y1 – y2)^ 2)计算2点之间的距离.我的第一点有mmx和mmy协调,第二点有ox和oy协调.我的问题很简单,有没有更快的方法来计算这个? private function dist(m
private function dist(mmx:int, mmy:int, ox:int, oy:int):Number{
return Math.sqrt((mmx-ox)*(mmx-ox)+(mmy-oy)*(mmy-oy));
}
这是我的代码,谢谢你的帮助.
public function moveIT(Xmouse, Ymouse):void{
f = Point.distance( new Point( Xmouse, Ymouse ), new Point( mainSP.x, mainSP.y ) );// distance between mouse and instance
distancePro = Point.distance( pointO, new Point( mainSP.x, mainSP.y ) );// distance from start point
if ( f < strtSen ){ // move forward
tt.stop(); tt.reset(); // delay timer on destination
mF = true; mB = false;
ag = Math.atan2((Ymouse - mainSP.y),(Xmouse - mainSP.x)); // move-forward angle, between mouse and instance
}
if (mF){ /// shoot loop
if (f > 5){// 5 pixel
mainSP.x -= Math.round( (400 /f) + .5 ) * Math.cos(ag);
mainSP.y -= Math.round( (400 /f) + .5 ) * Math.sin(ag);
}
if ( distancePro > backSen ){// (backSen = max distance)
mF = false;
tt.start();// delay timer on destination
}
}
if (mB){ /// return loop
if ( distancePro < 24 ){// back angle re-calculation
agBACK = Math.atan2((y1 - mainSP.y),(x1 - mainSP.x));
}
mainSP.x += (Math.cos(agBACK) * rturnSpeed);
mainSP.y += (Math.sin(agBACK) * rturnSpeed);
if ( distancePro < 4 ){ // fix position to start point (x1,y1)
mB = false;
mainSP.x = x1; mainSP.y = y1;
}
}
}
private function scTimer(evt:TimerEvent):void {// timer
tt.stop();
agBACK = Math.atan2((y1 - mainSP.y),(x1 - mainSP.x));// move-back angle between start point and instance
mB = true;
}
另外:pointO = new Point(x1,y1);设定起点.我不能使用mouseX和mouseY,因为父类调用应用程序的方式,所以我可以将x和y传递给我的循环.
调用静态函数有点贵.您可以通过执行以下操作来节省开销:private var sqrtFunc = Math.sqrt;
private function dist(mmx:int, mmy:int, ox:int, oy:int):Number{
return sqrtFunc((mmx-ox)*(mmx-ox)+(mmy-oy)*(mmy-oy));
}
