I would like to create an intelligent (universal) class to looping movement object, like sliding doors, etc.

I've thought to declare two vectors:

From To

And a Speed variable.

Then looping. I don't know how to check when current position is >= then To and looping reverse, considering that you can have starting position (x or y or z) greater then arriving position.



1 Answer 1


I'd solve this by abstracting your loop phase from the position, something like this:

phase = phase + deltaTime/travelTime;

// Here I use a cosine wave to get a nice ease-in and -out.
// You could use a triangle wave instead for linear motion.
weight = 0.5 * (1 - cos(phase * PI))

position = lerp(From, To, weight);

Here when phase is 0, you're at From, about to start moving toward To. At 0.5, you're halfway from From to To. At phase = 1.0, the object has arrived at To and is about to turn around and return to From. At 1.5, it's halfway back to From. And at 2.0 the cycle repeats (you could take phase modulo 2 for the same effect).


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .