This year, I entered the WWDC 2015 Scholarships competition. I didn’t win, but there were a couple of interesting parts of my app that I thought were still worth sharing.
My design centred around rising and falling blocks that represented the different parts of my life. These blocks had mass and density and elasticity, and they responded in a lively way. And, like little blocks in a glass case, I wanted them to fall away when the device rotated.
I tried doing this by animating blocks from one side of the device to the other, but it just didn’t feel right. The blocks needed to be physical. I needed a physics engine: UIKit Dynamics.
The first step to this is to get the blocks falling down the device in a realistic way. The second step is to listen for device orientation changes, and update our blocks in response to these changes.
Skip to the end if you want to see the code in its entirety.
We set up a new empty view, and add a green and an orange block.
We also add a UIDynamicAnimator, which controls the physics for the system. We add a UIGravityBehavior, for replicating gravity, and collisions and elasticity between the items.
Then we need to add all of these components to our master animator, and tweak the the elasticity of the blocks so they’re more bouncy.
At this stage, our view controller will be something like (regularGravityVector and invertedGravityVector are not needed yet, but will be useful later).
We can build and run our project, and see the cool falling-blocks effect.
To achieve the cool effect of blocks-in-a-box, we wanted to be able to rotate the device and have the gravity flip around. This is super easy to implement, thanks to the setup we did earlier.
We listen for the device’s orientation changes
and add our handling of the orientation changes
This will receive all of the orientation changes, and handle the portrait-to-upside-down changes. All that’s left is to flip the gravity.
Perfect! Now we get the falling blocks we wanted.
Putting it all together, we end up with something like
My products
💅 Vanilla – hide icons from your Mac menu bar for free
🚀 Rocket – super-fast emoji shortcuts everywhere on Mac… :clap: → 👏
⏳ Horo – the best free timer app for Mac
📂 FastFolderFinder – a lightning-fast launchbar app for folders and apps
📖 Kubernetes – my book on Kubernetes for web app developers
😄 Emoji Bullet List – easily emojify your bullet point lists (like this one!)
Jump on my email list to get sent the stuff that’s too raunchy for the blog. (Seriously though, it’s an occasional update on apps I’ve built and posts I’ve written recently.)