13

如何在 touchmoved 功能中获取手指运动的速度和方向?

我想获取手指速度和手指方向并将其应用于 UIView 类方向移动和动画速度。

我读了这个链接,但我无法理解答案,此外它没有解释我如何检测方向:

UITouch 移动速度检测

到目前为止,我尝试了这段代码:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *anyTouch = [touches anyObject];
    CGPoint touchLocation = [anyTouch locationInView:self.view];
    //NSLog(@"touch %f", touchLocation.x);
    player.center = touchLocation;
    [player setNeedsDisplay];
    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 = [self distanceBetweenPoints:location :prevLocation];
    NSTimeInterval timeSincePrevious = event.timestamp - previousTimestamp;

    NSLog(@"diff time %f", timeSincePrevious);
}
4

2 回答 2

21

方向将根据 touchesMoved 中的“location”和“prevLocation”的值确定。具体来说,位置将包含新的触摸点。例如:

if (location.x - prevLocation.x > 0) {
    //finger touch went right
} else {
    //finger touch went left
}
if (location.y - prevLocation.y > 0) {
    //finger touch went upwards
} else {
    //finger touch went downwards
}

现在 touchesMoved 将针对给定的手指移动多次调用。将手指第一次触摸屏幕时的初始值与最终完成移动时的 CGPoint 值进行比较将是代码的关键。

于 2012-04-22T20:57:46.437 回答
8

为什么不只是以下作为 obuseme 回应的变体

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

         UITouch *aTouch = [touches anyObject];
         CGPoint newLocation = [aTouch locationInView:self.view];
         CGPoint prevLocation = [aTouch previousLocationInView:self.view];

         if (newLocation.x > prevLocation.x) {
                 //finger touch went right
         } else {
                 //finger touch went left
         }
         if (newLocation.y > prevLocation.y) {
                 //finger touch went upwards
         } else {
                 //finger touch went downwards
         }
}
于 2012-10-19T22:04:07.343 回答