Problem: move an object along a straight line at a constant speed in the Cartesian coordinate system (x,y only). The rate of update is unstable. The movement speed must be close to exact and the object must arrive very close to the destination. The line’s source and destination may be anywhere.
Given: the source and destination addresses (x0,x1,y0, y1), and a speed of arbitrary value.
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.
Here’s what I’ve got:
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?
basic physics to the rescue
total time spent traveling = distance/speed
btw
Math.hypot(limitX,limitY)is faster thanMath.sqrt(Math.pow(limitX, 2) + Math.pow(limitY, 2))though really it’s that while loop you should refactor out