The sample code project, HapticBounce, demonstrates how to play a haptic with audio when a bouncing sphere collides with the edges of the screen. The sample app shows how to vary the volume of the synthesized audio signal and the intensity of the transient haptic pattern based on the sphere’s velocity during impact.
Although the sample app uses UIKit Dynamics and UIKit for simplicity and familiarity with UIKit classes, but your app can also use a 2D engine like SpriteKit to represent interactive object collisions.
Configure the App to Play Haptics
Check for device compatibility and set up an instance of CHHapticEngine, as the sample demonstrates when you launch the app.
Each bounce against the wall is a dynamic item behavior, which lets you tweak the elasticity to match the haptic effect. An animator of class UIDynamicBehavior ties together all of these dynamic objects with gravity.
HapticBounce uses the device’s accelerometer to move the sphere. It adjusts the accelerometer by responding to motion updates in a completion handler.
Play Variable Haptic Patterns on Collision
When the sphere collides with a wall, the dynamics framework sends a callback to its delegate. ViewController implements this delegate, UICollisionBehaviorDelegate, to respond to collisions.
To vary the haptic at the point of collision, check the sphere’s velocity and map it to a normalized (0 to 1) intensity and sharpness value, as follows:
The sample sets kMaxVelocity based on experimentation dropping the sphere from a maximum possible height, but you can adjust the value to create a stronger or weaker intensity pattern.
On each impact, you can create a haptic player, an inexpensive operation, on the spot, using the desired haptic parameters.
Starting the player plays the haptic.
Synthesize Audio to Play With the Haptic
In addition to playing haptic patterns, the haptic engine also synthesizes audio. The engine in HapticBounce plays this audio by adding an audio event to the same haptic player as the haptic event, as follows:
Instead of adjusting haptic intensity and sharpness based on the sphere’s velocity, you vary audio volume and pitch.