We publish our games on both Mac and iOS. Since UIKit is not available on Mac, we have to build all of our UI by hand in Cocos2D. One of the hardest parts to get right was emulating the UIScrollView bouncy scroll formula. Here it is in action:
There are tons of implementations available in nearly every language and framework, but few of them nail all the important properties of the UIKit scroll:
When the user is touching the screen: the page should be glued to their finger. Easy enough.
After the user flicks the screen and lets go: the page should “glide”, decelerating slowly until it comes to a stop. Most implementations get this half-right because it’s also pretty easy: just multiply the velocity by a decay factor (we use 0.95) every frame. The real pitfall lies in calculating the velocity at the moment the user lets go of the page. Here’s the naive implementation:
This works most of the time, but you may find that occasionally the page flies off at warp speed after a very light touch. The reason is that while the user is removing their finger from the screen, their fingertrip is actually changing shape. The center of that shape may move very quickly at the exact instant they release their finger, even if the finger as a whole has only moved straight away from the screen. The solution is not to calculate the velocity when the touch is ended, but to filter the velocity continually like so:
When the page is gliding and it hits the bottom: this is where some implementations start to break down. The page should go past the edge and elastically snap back. Many implementations just stop the page immediately, or worse, bounce off the bottom inelastically.
When the user has their finger on the screen and tries to scroll past the edge (overscroll): a lot of implementations keep the page glued to the user's finger when this happens. It's easy to miss, but UIKit actually slows the scroll down to about 40% of the normal speed.
And that's it! The results speak for themselves. Happy scrolling!