UITouch movement speed detection

iphone, objective-c

Solution

You could try (zero out distanceSinceStart and timeSinceStart in touchesBegan):

distanceSinceStart = distanceSinceStart + distanceFromPrevious;
timeSinceStart = timeSincestart + timeSincePrevious;
speed = distanceSinceStart/timeSinceStart;

which will give you the average speed since you started the touch (total distance/total time).

Or you could do a moving average of the speed, perhaps an exponential moving average:

const float lambda = 0.8f; // the closer to 1 the higher weight to the next touch

newSpeed = (1.0 - lambda) * oldSpeed + lambda* (distanceFromPrevious/timeSincePrevious);
oldSpeed = newSpeed;

You can adjust lambda to values near 1 if you want to give more weight to recent values.

Problem

I'm trying to detect the speed of touch movement and i'm not always getting the results I'd expect. (added: Speed spikes around too much) Can anyone spot if i'm doing something funky or suggest a better way of doing it ? ``` - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ self.previousTimestamp = event.timestamp; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [touches anyObject]; CGPoint location = [touch locationInView:self.view]; CGPoint prevLocation = [touch previousLocationInView:self.view]; CGFloat distanceFromPrevious = distanceBetweenPoints(location,prevLocation); NSTimeInterval timeSincePrevious = event.timestamp - self.previousTimestamp; CGFloat speed = distanceFromPrevious/timeSincePrevious; self.previousTimestamp = event.timestamp; NSLog(@"dist %f | time %f | speed %f",distanceFromPrevious, timeSincePrevious, speed); } ```

Original source