UITouch touchesMoved Finger Direction and Speed

回眸只為那壹抹淺笑 提交于 2019-12-03 16:48:30

问题


How can I get Speed and Direction of finger movements in touchmoved function?

I want to get the finger speed and finger direction and apply it in a UIView class direction movement and animation speed.

I read this link but I can not understand the answer, in addition it is not explaining how I can detect the direction:

UITouch movement speed detection

so far, I tried this code:

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

回答1:


Direction will be determined from the values of "location" and "prevLocation" in touchesMoved. Specifically, location will contain the new point of the touch. For example:

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
}

Now touchesMoved will get called many times for a given finger movement. It will be key to your code to compare an initial value when the finger first touches the screen, with a value of the CGPoint when the movement is finally complete.




回答2:


why not just the below as a variation on obuseme's response

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


来源:https://stackoverflow.com/questions/10271883/uitouch-touchesmoved-finger-direction-and-speed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!