我试图检测触摸运动的速度,但我并不总是能得到我所期望的结果。(补充说:速度太快了),,有人能发现我是不是在做一些古怪的事情,或者建议一种更好的方法吗?
- (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);
}发布于 2009-03-21 02:46:34
您可以尝试( distanceSinceStart中的零输出和touchesBegan中的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的值。
发布于 2012-07-31 11:36:06
主要问题是,当timeSincePrevious非常小(几毫秒)时,速度计算将非常不准确。要看这个,假设timeSincePrevious是1ms。如果distanceFromPrevious为0,则计算速度为0,如果distanceFromZero为1,则为1000。
因此,我建议lambda的值如下:
const float labmda = (timeSincePrevious>0.2? 1: timeSincePrevious/0.2);
也就是说,当timeSincePrevious很小时,我们使用一个很小的lambda。
https://stackoverflow.com/questions/668247
复制相似问题