Geeks With Blogs
Freestyle Coding Programming in the Real World

Today, I just wanted to share a quick WP7 gesture trick. When you're using FreeDrag gesture, you get a lot of sample points every time you get an update1. Instead of processing them all, you really only need to process two.

It sometimes seems a little confusing. The GestureSample returned by ReadGesture contains a Vector2 member called Position. This guy isn't really a "vector." He's is just a screen coordinate for the sample point.

As said above, ReadGesture will return multiple samples per Update. If you're doing something where you actually care about the path2, then every one is necessary. However, if you're just trying to drag a finger while a sprite moves in a one-to-one correspondence, then this is overkill.

Let us remember our vector math. We are trying to find the quickest point between a start and an end. Of course, this is a straight line. It is perfectly valid to add all of the vectors between the points. It is just completely unnecessary.

Here is the code to generate this one vector:

// If you had a known starting point, you could set _firstSample to that.
// This would drop the if check in the loop.
Vector2 _firstSample = Vector2.Zero, _lastSample = Vector2.Zero;

while( TouchPanel.IsGestureAvailable ) {
GestureSample _sample = TouchPanel.ReadGesture();

// This assumes you have only enabled the FreeDrag Gesture
// If you have multiple gestures enabled, you would have to check which sample you had.
// Think switch statement.
if( _firstSample == Vector2.Zero ) {
_firstSample = _sample.Position;
}

_lastSample = _sample.Position;
}

// This is the net change for the frame.
// Just add this guy to the current position.
Vector2 _delta = _firstSample - _lastSample;

This is a subset of the code used in the Windows Phone code sample in the downloads section. That code uses multiple GestureTypes and uses the switch statement referenced in the comment above. However, it illustrates the point that the entire set of samples is not needed to calculate the offset.

I will also mention that, yes, I do know about the bug in that code. We always calculate between the first ant last sample. However, the distance between the last sample of one Update and the first sample of the next Update is never included. Again, if your NEED every sample, you would have to account for this. In most cases, we are referring the the space your finger can move in 0.002222… second3. It will generally be negligible.

Happy coding.

1I seem to average about 15 FreeDrag samples per call to Update.
2Imagine a situation where you are tracing the outline of an image.
3For those of you playing our home game that is 1/15 of 1/30 of a second.

Posted on Friday, July 22, 2011 8:28 PM C# , XNA , Windows Phone | Back to top


Comments on this post: Quick FreeDrag Optimization Tip

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Chris Gardner | Powered by: GeeksWithBlogs.net