[Math] “reverse” percentage (go backward instead of forward)

percentages

I'm a bit stuck with calculations to my program here..
This is how it works today:
http://dropthebit.com/demos/pathAnimator/index.html

The object goes along the path, which the default is "forward", in a given time T and there are calculations running at 60 times a second, which determine the percentage from 0 to 100 of the object location along the path. I need to reverse that motion (in a click of a button), meaning the same calculations are still running, only now there will be a flag reverse turned on.

My problem is how to go, from the point I am now at, (in percentages) back and not to advance.

Here is the main logic of the code which runs at 60fps: (duration is in seconds)

elapsed = (now-startTime)/1000,
t = elapsed/duration, 
percent = t * 100;

if( that.reverse ){
   // i need to change the "percent" here somehow so it'll go backwards...
}

.. things happen...

I hope I was clear with everything.. Thanks!

Best Answer

Well...you're mostly in trouble. You cannot possibly calculate the thing you want without (at later points in the loop) knowing when you changed direction.

I'm going to suggest that if you don't need "startTime" in any other place in your code, you treat it as "the time at which I started moving in my current direction"; you'll also need another variable, startPosition, which will be zero in your current code, and direction, which will be $+1$ or $-1$. Then things looks like this:

//initialization
startPosition = 0;
direction = 1;
startTime = 0

// ...other code here


elapsed = (now-startTime)/1000,
t = elapsed/duration; 
percent = (t + startPosition) * 100;
if (percent >= 100){
   percent = 100;
   direction = -1;
   startTime = now;
   startPosition = 100;
}
elseif (percent <= 0){
   percent = 0;
   direction = 1;
   startTime = now;
   startPosition = 0;
}

if( that.reverse ){
   startPosition = percent;
   startTime = now;
   direction = -direction;
}

I've been a little sloppy here, in the sense that when you too a step a little past 100%, I treated it as being 100%, and startedmoving backwards, and similarly at 0%. You COULD do careful truncation and fractional part stuff, but it's almost certainly not necessary, so keep it simple.

Related Question