2011-06-09 69 views
3

問題:在笛卡爾座標系(僅x,y)中以恆定速度沿直線移動對象。更新率不穩定。移動速度必須接近確切,物體必須非常靠近目的地。線路的來源和目的地可能在任何地方。以恆定速度沿着直線移動鴕鳥的高效算法

鑑於:源地址和目標地址(x0,x1,y0,y1)以及任意值的速度。

一個幫助:SO有一個關於這個問題的答案,它很好,但它假設給出了總旅行時間。

下面是我得到了什麼:

 
x0 = 127; 
y0 = 127; 
x1 = 257; 
y1 = 188; 
speed = 127; 
ostrich.x=x0 //plus some distance along the line; 
ostrich.y=y0 // plus some distance along the line; 
//An arbitrarily large value so that each iteration increments the distance a minute amount 
SPEED_VAR = 1000; 
xDistPerIteration = (x1 - x0)/SPEED_VAR; 
yDistPerIteration = (y1 - y0)/SPEED_VAR; 
distanceToTravel = ;//Pythagorean theorum 
limitX = limit1 = 0; //determines when to stop the while loop 

//get called 40-60 times per second void update(){ //Keep incrementing the ostrich' location while (limitX < speed && limitY < speed) { limitX += Math.abs(xDistPerIteration); limitY += Math.abs(yDistPerIteration); ostrich.x += xDistPerIteration; ostrich.y += yDistPerIteration; } distanceTraveled -= Math.sqrt(Math.pow(limitX, 2) + Math.pow(limitY, 2)); if (distanceTraveled <=0) //ostrich arrived safely at the factory }

This code gets the job done, however it takes up exclusively 18% of program time in a CPU intensive program. It's garbage, programatically and in terms of performance. Any ideas on what to do here?

+7

這是作業,或者你在一個擁有一些_very_訓練有素的鴕鳥的動物園裏工作:-) – paxdiablo 2011-06-09 02:22:49

+1

你是什麼意思「不同斜率的直線」? – takteek 2011-06-09 02:23:15

+0

@paxdiablo Nah,而不是HW。我的MS程序不分配有趣的問題。 @takteek指出。 – 2011-06-09 02:38:44

回答

2

An asside: There is an answer on the SO regarding this, and it's good, however it presumes that total time spend traveling is given.

basic physics to the rescue

total time spent traveling = distance/speed

btw Math.hypot(limitX,limitY)快於Math.sqrt(Math.pow(limitX, 2) + Math.pow(limitY, 2))

但實際上它是while循環,你應該重構出

+1

我已經使用了Math.sqrt(Math.pow)...)數百次。哇。 – 2011-06-09 02:45:00

+1

@farm Math.pow(x,2)也比(x * x)慢得多(儘管如此,取決於底層實現,有些檢查exp arg中的低整數值並優化它,但不要指望它) – 2011-06-09 02:50:00

+0

感謝您的提示。都好。我簡直不敢相信我錯過了......我用了1-3的速度,但距離/速度超出了我。 – 2011-06-09 02:56:10

1

有一兩件事要改善的是:

沒有必要計算每次調用更新函數的平方根。您可以改用平方distanceTraveled

同樣,Math.abs(xDistPerIteration)Math.abs(yDistPerIteration)在每次調用更新時都不會更改,您可以保存這些值並去除絕對值函數的調用,從而節省多一點的計算時間。

+0

感謝您的指點。都是真的。雖然這是殺手的循環。 – 2011-06-09 02:45:43

1

Update被稱爲每秒40-60次,對吧?換句話說,每幀一次。那麼爲什麼它裏面有一個while循環呢?

另外,做sqrt一次,pow兩次,每幀是不必要的。 只要讓d2爲距離平方,並在limitX*limitX+limitY*limitY超過它時停止。