Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to move an object from point(x1,y1) to point(x2,y2) at a given speed in a straight line in java

Tags:

java

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.

like image 305
agnes Avatar asked Nov 18 '25 00:11

agnes


1 Answers

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:

  1. [Given: start_time, total_time, x0, y0, x1, y1]
  2. put the circle at (x0, y0) and set time_now = start_time
  3. until time_now == start_time + total_time, calculate (x, y) using the above, move the circle to (x, y), and increment time_now.

The time increment can be regular wall-clock time as determined by System.getTimeMillis().

like image 196
Ted Hopp Avatar answered Nov 20 '25 13:11

Ted Hopp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!