Reputation: 1232
How would I write a function to move from point1 to point2 given some time?
For example:
Point move(Point point1, Point point2, long timeInMilliseconds, int speedPerSecond)
{
// basic stuff
int pointsMoved = speedPerSecond * 1000 / timeInMilliseconds;
if (point1.x == point2.x && point1.y > point2.y)
return (new Point(point1.x, Math.min(point2.y, point1.y + pointsMoved)));
...
}
Yes, that's where my sad math skills end. How do I move if the movement is not diagonal or vertical? if there's an angle?
BTW, I plan to recalculate the current point based on point1 and point2, I will not be updating point1 nor point2 from the caller, so caller would look like this:
Point currentPoint = move(originalPoint, finalPoint, getCurrentTime() - originalTime, 10);
The signature of the function doesn't have to be what I mentioned. It could very well use degrees, but that's going to be another thing to figure out, if I have to use degrees.
Upvotes: 1
Views: 245
Reputation: 799390
Here's the general motion formula:
p = k⟨p2 - p1⟩ + p1
p1 is the initial position. p2 is the final position. p is the current location. k is a ratio, usually between 0 and 1, that determines how much of the distance to p2 we've covered.
Your function receives tn, the current time, and v, the speed from the p1 to p2. Therefore we need one additional piece to calculate k: the distance from p1 to p2. tn is in time units (t), the distance |p2 - p1| is in distance units (d), and the speed is in distance per time units (d / t). k is unitless, so we have to neutralize the units in the three values.
d / (d / t) / t
= d / d · t / t
= 1
and our units are neutralized.
So we have:
k = |p2 - p1| / v / tn
The distance is easily determined via the Pythagorean Theorem, giving us k. From there we decompose the general formula into its components:
px = k(x2 - x1) + x1
py = k(y2 - y1) + y1
k, being unitless despite containing elements with components, does not get decomposed.
Upvotes: 3