【发布时间】: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