How would I calculate the scrolling momentum for a scroll event?
I understand that there have to be two timestamps at the beginning of the scrolling at the end. There also has to be an “axis change” variable which is basically the amount to scroll by without inertia.
This is my current code responsible for ending of scrolling:
if ((type == kMXTEnd || type == kMXTMovedOut) && _isScrolling)
{
long int finishTime = MXTimestamp();
printf("SCEnd: Ending scroll at %ld\n",finishTime-_beginTime);
/* scrollX is the change in X axis */
/* finishTime is time from touch down to touch up */
printf(" * Time: %ld ChangeX: %f\n",finishTime,scrollX);
_isScrolling = FALSE;
_originalScrollPoint = _scrollPoint;
}
Is it possible to calculate an “inertia addition” for that? Like an additional offset gained by inertia which I can scroll by in addition to the primary scroll value. Or do I need to get additional variables?
I need this because I’m writing my own UI toolkit, which isn’t really based on anything.
You could simulate this with a “recent axis changes” queue.
If you store say the last half a second of changes with the corresponding timestamps, you can then test if the queue is longer than a value
N(ie if the user dragged it quicker than usual towards the end). You know the total distance traveled in the last half a second, the time, from those you can get a speed.Scale the speed to something reasonable (say.. for 15px/.5sec, map to ~25px/sec) and apply a negative acceleration (also appropiately scaled, for the example above, say -20px/sec) every couple of milliseconds (or as fast as your system can easily handle it, don’t overstress it with this).
Then run a timer, updating the speed at each tick (
speed+=accel*time_scale), then the position (position+=speed*time_scale). When the speed reaches 0 (or goes below it) kill the timer.