Creating Turbulence Effects with Animations - UI Dynamics - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 13. UI Dynamics

13.3 Creating Turbulence Effects with Animations

Problem

You want to simulate turbulence in your animator and have your UI components flail about when they hit the turbulent region.

Solution

Instantiate your turbulence with the turbulenceFieldWithSmoothness(_:animationSpeed:) class method of UIFieldBehavior. Then do the following:

1. Set the UIFieldBehavior class’s strength property according to your needs.

2. Set its region property to an instance of UIRegion. This defines in which region of the screen your turbulence behavior is effective.

3. Set its position property to a CGPoint instance in your reference view.

After you are done setting up the turbulence behavior, add it to your animator of type UIDynamicAnimator.

Discussion

In this recipe, I want to create an effect very similar to what we got in Recipe 13.2, but in addition add a turbulence field in the center of the screen so that, when we take our little orange view (see Figure 13-1) and drop it from the top let corner of the screen, it will fall down (and to the right, see Figure 13-4). But on its way down, it will hit our turbulence field and its movements will be affected.

Set up your gravity exactly as we did in Recipe 13.2. I won’t go through that here again. Then create a turbulence field in the center of the screen with a radius of 200 points:

lazy var turbulence: UIFieldBehavior = {

let turbulence = UIFieldBehavior.turbulenceFieldWithSmoothness(0.5,

animationSpeed: 60.0)

turbulence.strength = 12.0

turbulence.region = UIRegion(radius: 200.0)

turbulence.position = self.orangeView.bounds.size.center

turbulence.addItem(self.orangeView)

return turbulence

}()

Make sure to add this field to your animator. When the user is panning with the gesture recognizer (see Recipe 13.1), disable all your behaviors, and re-enable them when the panning is finished:

override func viewDidLoad() {

super.viewDidLoad()

animator.addBehavior(collision)

animator.addBehavior(gravity)

animator.addBehavior(turbulence)

}

@IBAction func panning(sender: UIPanGestureRecognizer) {

switch sender.state{

case .Began:

collision.removeItem(orangeView)

gravity.removeItem(orangeView)

turbulence.removeItem(orangeView)

case .Changed:

orangeView.center = sender.locationInView(view)

case .Ended, .Cancelled:

collision.addItem(orangeView)

gravity.addItem(orangeView)

turbulence.addItem(orangeView)

default: ()

}

}

Give it a go and see the results for yourself. Drag the orange view from the top left corner of the screen and drop it. It will be dragged down and to the right, and when it hits the center of the screen (inside a radius of 200 points), it will wiggle around a bit because of turbulence.

See Also