我试图检测触摸运动的速度,我并不总是得到我期望的结果.(补充说:速度太快了)如果我正在做一些时髦或建议更好的方法,有人能发现吗?
- (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); }
Jim.. 11
你可以尝试(在touchesBegan中将distanceSinceStart和timeSinceStart归零):
distanceSinceStart = distanceSinceStart + distanceFromPrevious; timeSinceStart = timeSincestart + timeSincePrevious; speed = distanceSinceStart/timeSinceStart;
这将为您提供自开始触摸以来的平均速度(总距离/总时间).
或者你可以做一个移动平均速度,也许是一个指数移动平均线:
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;
如果要为最近的值赋予更多权重,可以将lambda调整为接近1的值.
你可以尝试(在touchesBegan中将distanceSinceStart和timeSinceStart归零):
distanceSinceStart = distanceSinceStart + distanceFromPrevious; timeSinceStart = timeSincestart + timeSincePrevious; speed = distanceSinceStart/timeSinceStart;
这将为您提供自开始触摸以来的平均速度(总距离/总时间).
或者你可以做一个移动平均速度,也许是一个指数移动平均线:
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;
如果要为最近的值赋予更多权重,可以将lambda调整为接近1的值.