UITouch touchesMoved手指的方向和速度(UITouch touchesMoved

2019-07-29 02: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);
}

Answer 1:

方向将从“位置”,并在touchesMoved“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的价值的变动终于完成时。



Answer 2:

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


文章来源: UITouch touchesMoved Finger Direction and Speed