【问题标题】:timestamp and calculating velocity of a swipe时间戳和计算滑动速度
【发布时间】:2012-06-17 00:43:38
【问题描述】:

嘿,我知道已经有一些关于此的帖子 - 但我仍然无法为我遇到的问题找到适当的答案。

刚接触 cocoa 和 iOS,我正在开发我的第一个 iOS 游戏。在这个游戏中,我希望能够计算用户滑动的速度。我很容易找到滑动动作中连续触摸之间的距离,但很难确定触摸之间经过的时间

  • touchesMoved: 中,我使用当前触摸进行计算,并将上次记录的触摸记录为 UITouch

  • touchesEnded:我现在想计算滑动的速度,但是当我做类似的事情时:

    double timeDelay = event.timestamp - self.previousTouch.timestamp;

这总是返回 0。

但是,使用 gcc 我可以看到这两个时间戳实际上并不相同。此外,经过检查,我发现这些事件的 NSTimeInterval 值的大小约为 10^(-300)。这似乎很奇怪,因为 NSTimeInterval 应该报告自系统启动以来的秒数,不是吗?

我还尝试跟踪上一次触摸的 NSDate 并将其与 [NSDate timeIntervalSinceNow] 结合使用。这产生了更奇怪的结果,每次都返回一个大约 6 的值。同样,由于 timerIntervalSinceNow 返回一个NSTimeInterval,这个值很奇怪。

我对时间戳有什么不了解的地方?事件? 对此的任何帮助将不胜感激! 感谢您的宝贵时间

一些支持代码:

在 sampleController.h 中:

@property(nonatomic) UITouch* previousTouch
@property(nonatomic) UITouch* currentTouch

在 sampleController.m 中:

@synthesize previousTouch = _previousTouch, currentTouch = _currentTouch;
...
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
       self.currentTouch = [[event allTouches] anyObject];
       // do stuff with currentTouch
}
...
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
       self.previousTouch = self.currentTouch;
       self.currentTouch = [[event allTouches] anyObject];
       // do stuff with currentTouch
}
...
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
       float distanceMoved = [self.touch locationInView:self.playView].x - 
              [self.touch previousLocationInView:self.playView].x;
       // attempt 1
       double timeElapsed = self.currentTouch.timestamp - self.previousTouch.timestamp;

       // attempt 2
       double timeElapsed = event.timestamp - self.previousTouch.timestamp;

       // do stuff with distanceMoved and timeDelay
}

【问题讨论】:

  • iOS5 在UIGestureRecognizer 中内置了这个功能。

标签: iphone ios timestamp swipe uitouch


【解决方案1】:

UIPanGestureRecognizer 有一个velocityInView 属性,您可能会发现它很有用。文档是here

您也可能会发现这个 ray wenderlich tutorial 信息丰富。

(这不是一个小问题 - 但是一些谷歌搜索会发现大量关于这类事情的材料。为更大的生活问题节省了所有的头发拉扯;-)

【讨论】:

  • 我知道 UIPanGestureRecognizer 但我也遇到了麻烦。也许更多关于我正在做的事情的背景;游戏是砖烧杯的种类,因此我经常使用 touchesBegan: 和 touchesMoved: 来更新桨等的状态。我已经尝试使用 UIPanGestureRecognizer 来单独使用目标动作选择器方法中的 [sender velocityInView:] 来更新滑动速度。但是,当这样做时,每当识别出 UIPanGesture 时,它​​都会以某种方式中断 touchesMoved: 功能。建议?
  • 抱歉,发现了 cancelsTouchesInView 属性。现在完美运行。
  • 顺便说一句,我发现默认的速度度量很烦人,因为如果您在平移、停止然后松开手指,速度是停止之前的值,而我喜欢它如果您真的停止,则为零。只有我觉得这很烦人吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-28
  • 1970-01-01
  • 2015-11-04
  • 1970-01-01
相关资源
最近更新 更多