swiftuikit-dynamicsuipushbehavior

Swift UIKit dynamics - Vary UIPushBehavior force magnitude by distance from center of source


Can someone suggest how I can vary the UIPushBehavior magnitude force by distance from source. To mirror the affect of the force of wind from a fan on another object. So the closer the object is to the fan the stronger the force.

if String(describing: identifier) == "fan1" {
                self.push = UIPushBehavior(items: [self.object], mode: .instantaneous)
                self.push.setAngle(.pi/4, magnitude: 1)
                self.animator.addBehavior(self.push)
                self.push.addItem(self.object)
                
            }


Solution

  • Use a UIFieldBehaviour to create a linear gravitational field in the direction of the fan. Then you can specify a falloff:

    var forceField: UIFieldBehaviour!
    
    // ...
    
    forceField = UIFieldBehavior.linearGravityField(direction: CGVector(dx: 1, dy: -5))
    
    // example values for a "fan" on the bottom left blowing mostly upwards:
    forceField.position = CGPoint(x: view.bounds.minX, y: view.bounds.maxY)
    forceField.region = UIRegion(radius: 3000)
    forceField.minimumRadius = 100
    forceField.falloff = 5
    forceField.strength = 10
    forceField.addItem(view1)
    forceField.addItem(view2)
    animator.addBehavior(forceField)
    

    Have fun playing around with these values!

    Adding collision, another gravity behaviour, and a dynamic item behaviour to two views, we get the following effect:

    enter image description here

    That feels like a fan on the bottom left to me!

    You can also choose a radial gravitational field positioned at where the fan is, if your fan is in a corner and blows "radially", but note that you should use a negative value for strength in that case to say that the field repels rather than attracts.