2012-04-22 189 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