Method to move an object from point(x1,y1) to point(x2,y2) at a given speed in a straight line in 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 i开发者_如何学Pythonn 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:
- [Given: start_time, total_time, x0, y0, x1, y1]
- put the circle at (x0, y0) and set time_now = start_time
- 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()
.
精彩评论