一种有效的算法,以恒定的速度沿着一条线移动鸵鸟
问题:在笛卡尔坐标系中以恒定速度沿直线移动对象(仅限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 }
此代码完成了工作,但在CPU密集型程序中,它只占用了18%的程序时间。 它是垃圾,编程和性能方面。 关于该怎么做的任何想法?
一个助手:关于这一点,SO有一个答案,这很好,但是它假设花费了总的旅行时间。
救援的基本物理
旅行的总时间=距离/速度
btw Math.hypot(limitX,limitY)
比Math.sqrt(Math.pow(limitX, 2) + Math.pow(limitY, 2))
虽然真的是那个循环你应该重构出来
要改进的一件事是:
无需在每次调用更新函数时计算平方根。 您可以使用平方distanceTraveled
。
类似地, Math.abs(xDistPerIteration)
和Math.abs(yDistPerIteration)
在每次调用更新时都不会更改,您可以保存这些值并摆脱对绝对值函数的调用,以便为保存更多位计算时间。
Update
每秒调用40-60次,对吗? 换句话说,每帧一次。 那么为什么里面有一个while
循环呢?
此外,每帧执行一次sqrt
和pow
两次是不必要的。 让d2
为距离平方,当limitX*limitX+limitY*limitY
超过它时停止。