Efficient algorithm for moving ostriches along a line at a constant speed

Task: move the object in a straight line at a constant speed in the Cartesian coordinate system (only x, y). Update rate is unstable. The speed should be close to accurate, and the object should be very close to the destination. The source and destination of the line can be anywhere.

Data: source and destination address (x0, x1, y0, y1) and the speed of an arbitrary value.

Answer: there is an answer to SO regarding this, and this is good, but it assumes that the total travel time is given.

Here is what I have:


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 }

, 18% . , . , ?

+3
3

: , , , .

= /

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

, while

+2

:

. distanceTraveled.

, Math.abs(xDistPerIteration) Math.abs(yDistPerIteration) , , .

+1

Updatereceives a call 40-60 times per second, right? In other words, once per frame. So why is there a loop in it while?

In addition, doing sqrtonce and powtwice for each frame is not necessary. Just let it d2be the square of the distance and stop when it limitX*limitX+limitY*limitYexceeds it.

+1
source

All Articles