I use this function a lot in game/graphics programming.
float slide(float from, float to, float by) {
float difference = to - from;
if(difference > by) {
return from + by;
} else if(difference < -by) {
return from - by;
} else {
return to;
}
}
The basic idea is “move towards so-and-so by this much”.
I’ve called it slide because if you call it each frame on something’s position, it appears as sliding with constant speed towards a target position.
Any other suggestions for naming?
I think slide is OK, maybe moveTo or floatTo would be also OK.
And one more idea. when you use this function like this:
(menaing that “by” is bigger than possible step)
and you’ll call it several times, the object will oscilate around “to” position.
You should add some handling for it. Like:
hope this will help.