2012-04-22 194 views
11

如何获得touchmoved功能中手指运动的速度和方向?UITouch touchesMoved手指方向和速度

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

我看了这个链接,但我不明白的答案,除了它没有解释如何检测方向:

UITouch movement speed detection

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

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

回答

17

方向将根据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值。

+0

请检查这一点,我也比较触动,但它越变越慢http://stackoverflow.com/questions/21952274/how-多点触控顺序 – Ranjit 2014-02-24 12:38:45

+0

请编辑有关上下方向的注释,它们相反 – Garnik 2014-11-03 21:29:01

5

为什么不只是下面作为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 
     } 
} 
+0

请勿忘记'[超级触动移动:触及事件:事件]'! :d – taber 2015-04-27 17:15:07