I have to write a method that moves an object (e.g. circle) in a straight line from one coordinate to another with a given speed. The object must get to the target point and stop. The speed correlates to the time in which it takes the object to reach the point (speed = 15 is equivalent to time = 15 ms for example). If someone could help me with the maths here, I would be garateful, please.
The interpolation formula for moving from point p0 to point p1 at constant speed is:
p(t) = p0*(1-t) + p1*t
where t is time that has been scaled to vary from 0 at the start to 1 at the end and p, p0, and p1 are (x,y) coordinate pairs. Since Java doesn't have a built-in way to write the interpolation formula, you just apply it to the x and y components in parallel. The result is:
t = (time_now - start_time) / total_time;
x = x0*(1-t) + x1*t;
y = y0*(1-t) * y1*t;
This is the core calculation. To get the object to move, you follow these steps:
The time increment can be regular wall-clock time as determined by System.getTimeMillis().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With