I suppose that you want to know the speed between successive movements , and not the average in a number of movements. The theory should be light enough to adapt if you have other requirements.
You need to know three things:
- Where is the touch now?
- Where was the touch before?
- How much time has passed since then?
Then just use Pythagoras to get the distance, and divide time by speed.
When you receive the touchhesMoved event, it will provide you with the current and previous position. All you need to add is a measure of time.
To do this, you will need the NSDate property in your class to calculate the time interval. You can initialize and release it in viewDidLoad / viewDidUnload or somewhere similar. In my example, mine is called lastTouchTime , it is saved and initialized as follows:
self.lastTouchTime = [NSDate date];
and I release it in a predictable way.
Your touchhesMoved event should 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); }
Sorry, if I made faux pas with any memory management, itβs still not very convenient for me to work with ObjectiveC. I'm sure someone can fix it if necessary!
Good luck freezing.
source share