Implementing "drag and throw" behavior with touches
26 May
There have been a number of recent posts on blogs concerning the number of touches the iPad can handle (e.g. see Matt Gremmel), and it seems that 11 is the max. There is another aspect of the touch screen that needs to be explored, and the is the “granularity” of the touchesMoved method. In order to explore the ups and downs with this method I will make a simple “drag and throw” demo.
For my app IsoCards I wanted to allow users to drag and throw cards around the table. This is seemingly a trivial thing with the iPhone SDK by using the touchesMoved and touchesEnded methods. Say we have a subclass of UIView that we want to make draggable and throwable. Then we could do the following:
- Add an instance variable
velocityto our class. - In the update loop for the class we simple add the velocity to the current position of the view.
- In the
touchesMovedmethod we snap the view to the current position of the touch. - In
touchesEndeduse the-locationInView:and-previousLocationInView:methods onUITouchto compute how far the dragging touch moved, and use that as the new velocity for the view.
With this simple, perhaps even naive, implementation of the throwing behavior I ran into a problem right away. In IsoCards, people’s first reaction was to do a quick, flicking motion with their finger in hopes of sending the card flying to another player’s hand. Unfortunately, the touchesMoved and/or touchesEnded method is not refreshed fast enough for this. If a touch moves too fast and is released quickly, the -locationInView: and -previousLocationInView: methods return points that are only a few pixels apart. The user is left with a frustrating experience by putting the energy into flicking the card with force, yet it will only float a few pixels away.
The solution is easy enough. Add another instance variable, call it “previousPosition”, which is updated to the previous location of a touch in the touchesMoved, and then use this value to compute the throwing velocity of the card.
I have made a video showing the difference between these two methods:
I have also added the Xcode project being shown in the above video to my github account. You can download it here.





