LERP - Linear Interpolation
I gave this answer for a similar problem some days ago, but here we go:
Linear Interpolation is a function that gives you a number between two numbers, based on the progress. You could actually, get a point between two points.
The Great Formula - How to calculate it
The general LERP Formula is given by pu = p0 + (p1 - p0) * u
. Where:
- pu: The result number
- p0: The initial number
- p1: The final number
- u: The progress. It is given in percentage, between 0 and 1.
How to get percentage
You may be wondering, "How can I get this percentage!?". Don't worry. It's like this: How much time the point will take to travel from the start point to the end point? Ok, now divide it by the time that has already passed. This will give you the percentage.
Something like this: percentage = currentTime / finalTime;
Calculating Vectors
To get a resultant vector, all you need to do is apply the formula two times, one for X component and one for Y component. Like so:
point.x = start.x + (final.x - start.x) * progress;
point.y = start.y + (final.y - start.y) * progress;
Some frameworks/engines allow you to do the above in a single operation on the vector:
point = start + (final - start) * progress;
// or even
point = start.lerp(final, progress);
Calculating variate time
You may want to have your points to travel at a 0.5 points speed, yea? So let's say, a longer distance should be traveled in a longer time.
You can do it as follow:
Get the distance length
For it, you'll need two things. Get the distance
vector, then find its length value.
distancevec = final - start;
distance = distancevec.length();
If you don't know vectors math, you can calculate a vector length with this formula: d = sqrt(pow(v.x, 2) + pow(v.y, 2));
.
Get the time it will take and update finaltime
.
This one is easy. As you want to have each tick travel a 0.5 length, we just have to do a simple division and see how many ticks we got.
finalTime = distance / 0.5f;
Done.
NOTICE: Maybe, this may not be the intended speed for you, but this is the right one. So you have a linear movement, even on diagonal moves.
If you apply x += 0.5f
and y += 0.5f
, the resultant speed would be different at diagonals (given by the length formula above)