Recipe: Using Acceleration to Move Onscreen Objects

With a bit of programming, the iPhone’s onboard accelerometer can make objects “move” around the screen, responding in real time to the way the user tilts the phone. Recipe 14-4 builds an animated butterfly that users can slide across the screen.

The secret to making this work lies in adding a “physics timer” to the program. Instead of responding directly to changes in acceleration, the way Recipe 14-3 does, the accelerometer handler measures the current forces. It’s up to the timer routine to apply those forces to the butterfly over time by changing its frame. Here are some key points to keep in mind:

As long as the direction of force remains the same, the butterfly accelerates. Its velocity ...

Get The Core iOS Developer’s Cookbook, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.