Objective:
The term "Gravity" seems to be very big in any industry field.
So what is gravity in Swift? That is to put the lifeless things on our mobile screen into the gravitational force. This allows them to exhibit the effect of a natural bounce that appears to fall down as a result of gravity and touches an object.
To do this, we need two sharp tools: UIKit dynamics and Motion Effects.
First, Introduction
1.UIKit Dynamics is a new technology introduced from iOS 7 and belongs to the physical engine of the UIKit framework. Ability to simulate and emulate physical phenomena in real life it allows us to add some behavior to the interface elements in the program so as to achieve the real action behavior such as gravity, spring and so on. You just need to register the interface elements in the engine and specify the physical behavior, and the rest will be handed over to the physics engine.
? Motion effects can create very cool parallax effects. Just like when you switch between the screen and on your iphone. It is based on the data calculation analysis provided by the Apple-provided gravity accelerator, which enables our interface elements to react according to the tilt direction of the mobile device.
2. The value of the physics engine
is widely used in game development, and the classic success story is "Angry Birds"
allowing developers to stay away from the physics formula. Achieve cool physics simulation results
Improve the game development efficiency, generate a lot of other good fun physics simulation game
3. Well-known 2D physics engine
box2d
Chipmunk
Ii. steps to use
To use uidynamic to achieve physical simulation effects. The approximate process such as the following
(1) Creates a physical emulator (by the way set the simulation scope)
(2) creates the corresponding physical simulation behavior (by adding a physical emulation Element)
(3) Adds physical simulation behavior to the physical emulator? Start simulation
Third, related instructions
1. Three Concepts
(1) who wants to perform physical simulations?
How does the physical emulation effect of the physical emulation element (Dynamic Item)
(2) run? How is the animation effect?
Physical emulation behavior (dynamic Behavior)
(3) enables physical simulation elements to run detailed physical simulation behavior
Physical emulator (Dynamic Animator)
2. Physical simulation Elements
Note: No matter what object can do physics The emulation element
is not physically emulated by any object
Physical simulation element elements:
Whatever complies with the Uidynamicitem protocol object
UIView has complied with the Uidynamicitem protocol by default, So no matter what UI controls can do physical emulation
Uicollectionviewlayoutattributes class defaults to the Uidynamicitem protocol
3. Physical emulation Behavior
(1) Uidynamic provides the following physical simulation behavior
Dynamic behavior can be added or removed at random time.
In addition, dynamic behavior can be combined and can be inherited. You can use the Addchildbehavior: method to create a composite behavior by using an instance of Uidynamicbehavior or a user-subclass Uidynamicbehavior. (but cannot use this method for system-provided behavior)
1. Adsorption behavior (uiattachmentbehavior): There is an object Uiattachmentbehavior, which is used to specify the connection between two power items (items or points), and when an item or point moves, the adsorbed item moves with it. Of course, this connection is not entirely static (static), the adsorbed item has two properties damping (damping) and oscillation (oscillation). These two properties determine how the behavior of the adsorbed item changes over time.
(1) Uiattachmentbehavior
Specifies the connection between two power items or power items and anchor points. The Power item default anchor point is in his center.
Step 1: Instantiate the Uiattachmentbehavior by using the Initwithitem.
2. Use the Addbehavior: method to add the behavior to the dynamic animation.
The ability to add to their own defined combinations of behaviors, false assumptions in the dynamic animation every step of changing behavior, can implement the inherited action method.
(2) Uiattachmentbehavior Instantiation Method
Convenience init! (Item:uidynamicitem, Attachedtoanchor point:cgpoint)//Instantiate Uiattachmentbehavior, connect the center of dynamic item to an anchor point.
Convenience init! (Item:uidynamicitem, Offsetfromcenter offset:uioffset, Attachedtoanchor point:cgpoint)//instantiation of Uiattachmentbehavior, Connects the specified point of the dynamic item (relative to the dynamic item center point) to an anchor point.
convenience init! (item item1: UIDynamicItem, attachedToItem item2: UIDynamicItem) // Instantiate UIAttachmentBehavior, connect the center of the dynamic item to the center of the dynamic item.
init! (item item1: UIDynamicItem, offsetFromCenter offset1: UIOffset, attachedToItem item2: UIDynamicItem, offsetFromCenter offset2: UIOffset) // Instantiate UIAttachmentBehavior, connect the specified point of the dynamic item (relative to the point of the dynamic item center) to a dynamic item The specified point.
(3) UIAttachmentBehavior often uses attributes:
var items: [AnyObject] {get} // Returns dynamic items connected by behavior.
var attachedBehaviorType: UIAttachmentBehaviorType {get} // The type of UIAttachmentBehavior. Enum (UIAttachmentBehaviorType.Items, .Anchor)
var anchorPoint: CGPoint // Anchor of anchor type UIAttachmentBehavior.
var length: CGFloat // distance between two adsorption points (floating point)
var damping: CGFloat // 1: damping value (floating point) critical (critical value) damping
var frequency: CGFloat // vibration frequency (floating point) in Hertz
2. Collision behavior (UICollisionBehavior): Specify a boundary through the object UICollisionBehavior, and let each dynamic item participate in the collision within the boundary.
The UICollisionBehavior object can also specify that these dynamics respond appropriately to collisions.
(1) UICollisionBehavior
Specifies that some dynamic items can collide with each other or with the UICollisionBehavior boundary.
Step 1. Use the init method to create UICollisionBehavior, use the addItem: method to add a dynamic item to it, or use initWithItems: to instantiate UICollisionBehavior.
2. Use addBehavior: method to add UICollisionBehavior to dynamic animation
(2) UICollisionBehavior instantiation method and management:
init! (items: [AnyObject]) // Instantiate UICollisionBehavior using dynamic item array
func addItem (item: UIDynamicItem) // Add dynamic item to UICollisionBehavior instance
func removeItem (item: UIDynamicItem) // Remove dynamic item
var items: [AnyObject] {get} // Returns the array of dynamic items in the UICollisionBehavior instance
var collisionMode: UICollisionBehaviorMode // Specify the collision type
static var Items: UICollisionBehaviorMode {get}
static var Boundaries: UICollisionBehaviorMode {get}
static var Everything: UICollisionBehaviorMode {get}
var translatesReferenceBoundsIntoBoundary: Bool // whether the boundary based on the relative coordinate system is valid
UICollisionBehavior has three methods for setting boundaries:
func setTranslatesReferenceBoundsIntoBoundarywithInsets (insets: UIEdgeInsets)
func addBoundaryWithIdentifier (identifier: NSCopying, forPath bezierPath: UIBezierPath)
func addBoundaryWithIdentifier (identifier: NSCopying, fromPoint p1: CGPoint, toPoint p2: CGPoint)
func boundaryWithIdentifier (identifier: NSCopying)-> UIBezierPath? // Return the Bézier curve boundary line corresponding to the specified identifier
func removeBoundaryWithIdentifier (identifier: NSCopying) // Remove the Bézier curve boundary corresponding to the specified identifier
var boundaryIdentifiers: [AnyObject]? {get} // Return all boundary identifiers of the UICollisionBehavior instance
func removeAllBoundaries ()
unowned (unsafe) var collisionDelegate: UICollisionBehaviorDelegate? // CollisionDelegate of the instance will respond to some callback methods of the collision
3. UIGravityBehavior: A gravity vector is assigned to the dynamic term through the object UIGravityBehavior. The dynamic term with the gravity vector will always accelerate in the direction of the gravity vector. Until there is a conflict with other dynamics or. Encountered a boundary.
(1) UIGravityBehavior instantiation method and management:
init (items: [AnyObject]) // Instantiate UIGravityBehavior using dynamic item array
func addItem (item: UIDynamicItem) // Add dynamic item to UIGravityBehavior instance
func removeItem (item: UIDynamicItem) // Remove dynamic item of UIGravityBehavior instance
var items: [AnyObject] {get} // Return the dynamic item array in UIGravityBehavior instance
// The default value for the gravity vector is (0.0, 1.0)
// The acceleration for a dynamic item subject to a (0.0, 1.0) gravity vector is downwards at 1000 points per second 2.
var gravityDirection: CGVector // Navigation direction, trend (range is (0.0, 1.0))
var angle: CGFloat // angle
var magnitude: CGFloat /// When the value of the angle angle is 0, the block will move horizontally to the right. As the value increases, the block changes its angle clockwise. We just want to simulate gravity in reality. Therefore, this property is generally not set. When not set, the default is to move down vertically. Magnitude is the rate attribute of gravity behavior. The larger the value, the faster the rate of decline. When the value of the magnitude attribute is 0, the cube will not decrease, so the minimum rate is 0.1.
func setAngle (angle: CGFloat, magnitude: CGFloat) // Set the angle and rate together
4. Push behavior (UIPushBehavior): Use the object UIPushBehavior to assign a continuous or instantaneous force vector to the power item.
(1) UIPushBehavior instantiation method and management:
init! (items: [AnyObject] !, mode: UIPushBehaviorMode)
func addItem (item: UIDynamicItem)
func removeItem (item: UIDynamicItem)
var items: [AnyObject] {get}
func targetOffsetFromCenterForItem (item: UIDynamicItem)-> UIOffset // offset
func setTargetOffsetFromCenter (o: UIOffset, forItem item: UIDynamicItem)
var mode: UIPushBehaviorMode {get} // push mode
var active: Bool
var angle: CGFloat // angle
// A continuous force vector with a magnitude of 1.0, applied to a 100 point x 100 point view whose density value is 1.0, results in view acceleration of 100 points per s ^ 2
var magnitude: CGFloat // rate
var pushDirection: CGVector // Pushing heading trend
func setAngle (angle: CGFloat, magnitude: CGFloat) // Set the angle and rate
5. Snap action (UISnapBehavior): Specify a snap point for the power item through the object UISnapBehavior. The power item will capture this capture point based on the effect of the configuration.
(1) UISnapBehavior instantiation method and management
// The point argument is expressed in the reference coordinate system
init! (item: UIDynamicItem, snapToPoint point: CGPoint)
var damping: CGFloat // damping value from 0.0 to 1.0. 0.0 is the least oscillation.
6. Dynamic element behavior (UIDynamicItemBehavior)
(1) UIDynamicItemBehavior
Step 1. Use the init method to create UICollisionBehavior, use the addItem: method to add a dynamic item to it, or use initWithItems: to instantiate UIDynamicItemBehavior.
2. Use addBehavior: method to add UIDynamicItemBehavior to dynamic animation
(2) UIDynamicItemBehavior instantiation method and management:
init (items: [AnyObject])
func addItem (item: UIDynamicItem)
func removeItem (item: UIDynamicItem)
var items: [AnyObject] {get}
var elasticity: CGFloat // Set the collision elasticity coefficient.
Range (0.0-1.0)
var friction: CGFloat // Set the friction coefficient.
var density: CGFloat// set the relative density 1 by default
var resistance: CGFloat // linear resistance coefficient.
(0--CGFLOAT_MAX)
var angularResistance: CGFloat // Set the angular resistance coefficient (0--CGFLOAT_MAX)
var allowsRotation: Bool // Set whether the dynamic item in the behavior can loop enough
// The linear velocity, expressed in points per second, that you want to add to the specified dynamic item
// If called before being associated to an animator, the behavior will accumulate values until being associated to an animator
func addLinearVelocity (velocity: CGPoint, forItem item: UIDynamicItem) // Add the linear velocity attribute to the dynamic item. Unit point
func linearVelocityForItem (item: UIDynamicItem)-> CGPoint
// The angular velocity, expressed in radians per second, that you want to add to the specified dynamic item
// If called before being associated to an animator, the behavior will accumulate values until being associated to an animator
func addAngularVelocity (velocity: CGFloat, forItem item: UIDynamicItem) // Add the angular velocity attribute to the dynamic item. Unit radian
func angularVelocityForItem (item: UIDynamicItem)-> CGFloat
Note: Suppose you add multiple UIDynamicItemBehavior instances to the same dynamic animation. Only a set of attribute descriptions will be applied (intersection?) When multiple UIDynamicItemBehavior instances are configured with the same attribute, the last one is used.
(2) Notes on physical simulation behavior
All the above physical simulation behaviors are inherited from UIDynamicBehavior
UIDynamicBehavior configuration:
func addChildBehavior (behavior: UIDynamicBehavior!) // Add child behavior to UIDynamicBehavior defined by yourself
func removeChildBehavior (behavior: UIDynamicBehavior) // Remove the child behavior of UIDynamicBehavior defined by yourself
var childBehaviors: [AnyObject] {get} // Return an array of child behaviors that define their own UIDynamicBehavior
// When running, the dynamic animator calls the action block on every animation step.
var action: (()-> Void)! // The block of statements that will be called at each step during the running of UIDynamicAnimator
func willMoveToAnimator (dynamicAnimator: UIDynamicAnimator?) // nil when being removed from an animator
var dynamicAnimator: UIDynamicAnimator? {get}
4.Physical Simulator
(1) Notes for physical simulator
It enables physical simulation elements to run physical simulation behaviors
It is an object of type UIDynamicAnimator
Provide context for dynamic behavior
? Determine the coordinate system according to the ref view
? Control power engine
? Maintain the state of dynamic behavior
(2) Initialization of UIDynamicAnimator
init (referenceView view: UIView)
view parameter: is a reference view. Represents the scope of physical simulation
(3) Common methods of UIDynamicAnimator
func addBehavior (behavior: UIDynamicBehavior!) // Add 1 physical simulation behavior
func removeBehavior (behavior: UIDynamicBehavior!) // Remove 1 physical simulation behavior
func removeAllBehaviors () // Remove all physics simulation behaviors previously added
func itemsInRect (rect: CGRect)-> [AnyObject] // Return all dynamic items that pass through the specified area.
func elapsedTime ()-> NSTimeInterval // Return the time interval from the start of the animation to the present.
func updateItemUsingCurrentState (item: UIDynamicItem) // (Updates the state of the dynamic item in the UIDynamicAnimator), the dynamic item is added to the UIDynamicAnimator. You changed the status of the dynamic item. You should use this method to update the status of the dynamic item
init (collectionViewLayout layout: UICollectionViewLayout) // Use dynamic animation on collection views. The coordinate system of the collection view layout is used as the coordinate system for dynamic behavior and dynamic items. The power item must be a UICollectionViewLayoutAttributes object. You can use setTranslatesReferenceBoundsIntoBoundaryWithInsets: to set the collision dynamic limit (relative to the coordinate system of the collection view layout). When the collection view layout changes, it will automatically call invalidateLayout, pause, and start power
func layoutAttributesForCellAtIndexPath (indexPath: NSIndexPath)-> UICollectionViewLayoutAttributes! // Returns the layout attributes of the collection view cell at the specified position
func layoutAttributesForSupplementaryViewOfKind (kind: String, atIndexPath indexPath: NSIndexPath)-> UICollectionViewLayoutAttributes! // Returns the layout attribute of the collection view cell (specified by kind) at the indexPath position.
func layoutAttributesForDecorationViewOfKind (decorationViewKind: String, atIndexPath indexPath: NSIndexPath)-> UICollectionViewLayoutAttributes! // Returns the collection view cell specified at indexPath (specified with decorationViewKind) layout property of the decorationView.
(4) Common attributes of UIDynamicAnimator
var referenceView: UIView? {get} // reference view
var behaviors: [AnyObject] {get} // All physical simulation behaviors added to the physical simulator
var running: Bool {get} // is physical simulation in progress
unowned (unsafe) var delegate: UIDynamicAnimatorDelegate? // Proxy object (can monitor the simulation process of the physical simulator, such as start and end)
(5) Agent of UIDynamicAnimator
protocol UIDynamicAnimatorDelegate: NSObjectProtocol {
optional func dynamicAnimatorWillResume (animator: UIDynamicAnimator) // UIDynamicAnimator will be called when it is about to start
optional func dynamicAnimatorDidPause (animator: UIDynamicAnimator) // Called when UIDynamicAnimator has stopped
}
UIKit gravity in Swift