UITouch移动速度检测 [英] UITouch movement speed detection

查看:140
本文介绍了UITouch移动速度检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检测触摸移动的速度,我并不总是得到我期望的结果。 (补充说:速度太快了) 有人可以发现我是在做一些时髦的事情还是建议更好的做法?

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);

}


推荐答案

<你可以尝试(在touchesBegan中将distanceSinceStart和timeSinceStart归零):

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;

如果要为最近的值赋予更多权重,可以将lambda调整为接近1的值。

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

这篇关于UITouch移动速度检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆