UITouch触及手指方向和速度

时间:2012-04-22 20:34:20

标签: iphone ios uitouch

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

我想获得手指速度和手指方向,并将其应用于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);
}

2 个答案:

答案 0 :(得分:19)

方向将根据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值进行比较将是您的代码的关键。

答案 1 :(得分:6)

为什么不将以下作为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
         }
}