UITouch触及手指方向和速度

Val*_*lav 12 iphone uitouch ios

如何在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);
}
Run Code Online (Sandbox Code Playgroud)

And*_*sek 20

方向将根据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
}
Run Code Online (Sandbox Code Playgroud)

现在,对于给定的手指移动,touchesMoved将被多次调用.这将是关键,你的代码进行比较的初始值当手指首次触摸屏幕,与CGPoint的价值的变动终于完成时.


小智 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
         }
}
Run Code Online (Sandbox Code Playgroud)