I want to track The speed Of the T开发者_JAVA技巧ouch moved in pixel /Second
Any Budy Having idea For ThisExcept the PanGesture Method
I'll assume you want to know the velocity between consecutive movements, and not an average over a series of movements. The theory should be easy enough to adapt if you have other requirements, though.
You will need to know three things:
- Where is the touch now?
- Where was the touch previously?
- How much time has passed since then?
Then just use Pythagoras to get your distance, and divide by time for speed.
When you get a touchesMoved event, it will provide the current and previous position for you. All you need to then add is a measure of time.
For that, you will want an NSDate property in your class to help calculate the time interval. You could initialise and release it in viewDidLoad / viewDidUnload, or somewhere similar. In my example, mine is called lastTouchTime, it is retained, and I initialised like this:
self.lastTouchTime = [NSDate date];
and I release it in the predictable way.
Your touchesMoved event should then look something like this:
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSArray *touchesArray = [touches allObjects];
UITouch *touch;
CGPoint ptTouch;
CGPoint ptPrevious;
NSDate *now = [[NSDate alloc] init];
NSTimeInterval interval = [now timeIntervalSinceDate:lastTouchTime];
[lastTouchTime release];
lastTouchTime = [[NSDate alloc] init];
[now release];
touch = [touchesArray objectAtIndex:0];
ptTouch = [touch locationInView:self.view];
ptPrevious = [touch previousLocationInView:self.view];
CGFloat xMove = ptTouch.x - ptPrevious.x;
CGFloat yMove = ptTouch.y - ptPrevious.y;
CGFloat distance = sqrt ((xMove * xMove) + (yMove * yMove));
NSLog (@"TimeInterval:%f", interval);
NSLog (@"Move:%5.2f, %5.2f", xMove, yMove);
NSLog (@"Distance:%5.2f", distance);
NSLog (@"Speed:%5.2f", distance / interval);
}
Apologies if I've made a faux pas with any memory management, I'm still not very comfortable with ObjectiveC's way of doing things. I'm sure somebody can correct it if necessary!
Good luck, Freezing.
精彩评论