iOS Development-Advanced article--uidynamic physics engine

Source: Internet
Author: User

First, uidynamic

1. Introduction
What is Uidynamic
Uidynamic is a new technology introduced from iOS 7 and belongs to the Uikit framework
Can be thought of as a physical engine capable of simulating and simulating physical phenomena in real life.
Gravity, elastic collisions and other phenomena

The value of the physics engine
Widely used in game development, the classic success story is "Angry Birds"
Enable developers to achieve cool physics simulations away from the physics equation
Improve the game development efficiency, produce more excellent fun physics simulation game

Well-known 2D physics engine
Box2d
Chipmunk


2. Steps to use
To use uidynamic to achieve physical simulation, the following steps are outlined below
Create a physical emulator (by the way, set the simulation scope)

Create the appropriate physical simulation behavior (by adding physical simulation elements by the way)

Add physical emulation behavior to the physical emulator? Start simulation


Two or three major concepts

Physical emulation Element (Dynamic Item)
Who wants to perform physical simulations?

Physical simulation Behavior (Dynamic Behavior)
What kind of physical simulation effect does it perform? What kind of animated effect?

Physical Emulator (Dynamic Animator)
Allow physical simulation elements to perform specific physical simulation behavior

1. Physical simulation elements
Attention
Not all objects can do physical simulation elements
Not all objects can be physically emulated

Which objects can make physical simulation elements
Any object that complies with the Uidynamicitem protocol
UIView has complied with the Uidynamicitem protocol by default, so any UI control can do a physical simulation
The Uicollectionviewlayoutattributes class also complies with the Uidynamicitem protocol by default

2. Physical simulation Behavior
The uidynamic provides several physical simulation behaviors

Uigravitybehavior: Gravity Behavior
Uicollisionbehavior: Collision Behavior
Uisnapbehavior: Snapping behavior
Uipushbehavior: Driving behavior
Uiattachmentbehavior: Adhesion behavior
Uidynamicitembehavior: Dynamic Elemental Behavior

Physical Simulation Behavior Notice
All of the above physical simulation behaviors are inherited from Uidynamicbehavior
All Uidynamicbehavior can be carried out independently.
When combined with multiple behaviors, you can achieve some more complex effects

3. Physical simulator

Physical Emulator Notes
It allows physical simulation elements to perform physical simulation behavior
It is an object of type Uidynamicanimator

1) Initialization of the Uidynamicanimator
-(Instancetype) Initwithreferenceview: (UIView *) view;
View parameter: is a reference view that represents the scope of a physical simulation


2) Common methods of Uidynamicanimator
-(void) Addbehavior: (Uidynamicbehavior *) behavior;
Add 1 physical emulation behavior

-(void) Removebehavior: (Uidynamicbehavior *) behavior;
Remove 1 Physical simulation behaviors

-(void) removeallbehaviors;
Remove any physical emulation behavior that was previously added


3) Common Properties of Uidynamicanimator
@property (nonatomic, readonly) uiview* Referenceview;
Reference view

@property (nonatomic, readonly, copy) nsarray* behaviors;
All physical emulation behaviors added to the physical emulator

@property (Nonatomic, readonly, getter = isrunning) BOOL running;
Whether physical emulation is in progress

@property (nonatomic, assign) ID <UIDynamicAnimatorDelegate> delegate;
Proxy object (a simulation process that listens to a physical emulator, such as Start and end)


Iii. gravity behavior (uigravitybehavior)

1. Introduction
Given the direction of gravity and acceleration, the object drops in the direction of gravity.

Initialization of the Uigravitybehavior
-(Instancetype) Initwithitems: (Nsarray *) items;
Item parameter: A physical simulation element is stored inside

Uigravitybehavior Common methods
-(void) AddItem: (ID <UIDynamicItem>) item;
Add 1 physical emulation elements

-(void) RemoveItem: (ID <UIDynamicItem>) item;
Remove 1 Physical simulation elements

2. Uigravitybehavior Common Properties
@property (nonatomic, readonly, copy) nsarray* items;
All the physical simulation elements added to the gravity behavior

@property (ReadWrite, nonatomic) Cgvector gravitydirection;
Gravity direction (is a two-dimensional vector)

@property (ReadWrite, nonatomic) cgfloat angle;
Gravity direction (is an angle, the positive direction of the X axis is 0°, clockwise positive, counterclockwise negative)

@property (ReadWrite, nonatomic) cgfloat magnitude;
Magnitude (used to control acceleration, 1.0 means acceleration is points/second²)

3, Actual combat drills

/** Physical Emulator*/@property (nonatomic, strong) Uidynamicanimator*animator, @property (weak, nonatomic) Iboutlet UIView*Blueview;-(Uidynamicanimator *) animator{if(!_animator) {        //Creating a physical emulator (Referenceview, referring to a view, is actually setting the simulation scope)_animator =[[Uidynamicanimator alloc] initWithReferenceView:self.view]; }    return_animator;} //1. Create physical simulation behavior-gravity behaviorUigravitybehavior *gravity =[[Uigravitybehavior alloc] init];    [Gravity AddItem:self.blueView]; //Gravity Direction//gravity.gravitydirection = cgvectormake (100, 100); //gravitational acceleration ()Gravity.magnitude =Ten; //point/s²//Distance traveled = magnitude * Time ²//2. Add physical emulation behavior to the physical emulator to start the physical simulation[Self.animator addbehavior:gravity];

Iv. collision Behavior (Uicollisionbehavior)

1. Introduction
Allows for collision between objects
Physical collisions can be confined to a space by adding boundaries (boundary)

Uicollisionbehavior boundary-related methods

-(void) Addboundarywithidentifier: (ID <NSCopying>) identifier Forpath: (uibezierpath*) Bezierpath;

-(void) Addboundarywithidentifier: (ID <NSCopying>) identifier frompoint: (Cgpoint) P1 topoint: (cgpoint) P2;

-(uibezierpath*) Boundarywithidentifier: (id <NSCopying>) identifier;

-(void) Removeboundarywithidentifier: (id <NSCopying>) identifier;

@property (nonatomic, readonly, copy) nsarray* boundaryidentifiers;


-(void) removeallboundaries;


2. Common usage of Uicollisionbehavior
@property (nonatomic, ReadWrite) BOOL translatesreferenceboundsintoboundary;
Whether to use the bounds of the reference view as the boundary

-(void) Settranslatesreferenceboundsintoboundarywithinsets: (uiedgeinsets) insets;
Set the bounds of the reference view to the boundary, and set the padding

@property (nonatomic, ReadWrite) Uicollisionbehaviormode Collisionmode;
Collision Mode (divided into 3 types, elemental collisions, boundary collisions, all collisions)

@property (nonatomic, assign, ReadWrite) ID <UICollisionBehaviorDelegate> collisiondelegate;
Proxy object (can listen for element collision process)

3. Collision Combat Drills

@property (Weak, nonatomic) Iboutlet Uisegmentedcontrol *Segmentcontrol;/** Physical Emulator*/@property (nonatomic, strong) Uidynamicanimator*animator, @property (weak, nonatomic) Iboutlet UIView*Blueview;-(Uidynamicanimator *) animator{if(!_animator) {        //Creating a physical emulator (Referenceview, referring to a view, is actually setting the simulation scope)_animator =[[Uidynamicanimator alloc] initWithReferenceView:self.view]; }    return_animator;} //1. Create Collision BehaviorUicollisionbehavior *collision =[[Uicollisionbehavior alloc] init]; //change the bounds of the reference view to the border of the collision detectionCollision.translatesreferenceboundsintoboundary =YES;    [Collision AddItem:self.blueView];        [Collision AddItem:self.segmentControl]; //2. Create physical simulation behavior-gravity behaviorUigravitybehavior *gravity =[[Uigravitybehavior alloc] init]; Gravity.magnitude= -;        [Gravity AddItem:self.blueView]; //3. Add Behavior[Self.animator addbehavior:collision]; [Self.animator addbehavior:gravity];

4. Collision drills--adding boundaries

//1. Create Collision BehaviorUicollisionbehavior *collision =[[Uicollisionbehavior alloc] init];    [Collision AddItem:self.blueView]; //[Collision AddItem:self.segmentControl]; //Add Boundary//cgfloat StartX = 0; //cgfloat starty = self.view.frame.size.height * 0.5; //cgfloat endx = self.view.frame.size.width; //cgfloat EndY = self.view.frame.size.height; //[Collision addboundarywithidentifier:@ "Line1" Frompoint:cgpointmake (StartX, Starty) topoint:cgpointmake (EndX,    EndY)]; //[Collision addboundarywithidentifier:@ "Line2" Frompoint:cgpointmake (endx, 0) topoint:cgpointmake (EndX, EndY)];< /c8>cgfloat Width=Self.view.frame.size.width; Uibezierpath*path = [Uibezierpath bezierpathwithovalinrect:cgrectmake (0,0, width, width)]; [Collision Addboundarywithidentifier:@"Circle"Forpath:path]; //2. Create physical simulation behavior-gravity behaviorUigravitybehavior *gravity =[[Uigravitybehavior alloc] init]; Gravity.magnitude=Ten;        [Gravity AddItem:self.blueView]; //3. Add Behavior[Self.animator addbehavior:collision]; [Self.animator addbehavior:gravity];

Slash boundary

Arcs as boundaries

V. Capture Behavior (Uisnapbehavior)

1. Introduction
The object can be quickly rushed to a position (snap position), the position will be captured with a certain vibration

Initialization of the Uisnapbehavior
-(Instancetype) Initwithitem: (ID <UIDynamicItem>) Item snaptopoint: (Cgpoint) point;

Uisnapbehavior Common Properties
@property (nonatomic, assign) CGFloat damping;
For reduction, damping (value range is 0.0 ~ 1.0, the greater the value, the smaller the amplitude of vibration)

Uisnapbehavior Use note
If you want to perform a continuous snapping behavior, you need to remove the preceding snapping behavior from the physical emulator first

2. Capturing Practical Drills

// get touch points    Uitouch *touch = [touches anyobject];     = [Touch LocationInView:self.view];         // create adsorption \ Snap Behavior    Uisnapbehavior *snap = [[Uisnapbehavior alloc] InitWithItem:self.blueView snaptopoint:point];     // Anti -shake factor (less value, more jitter)    1.0 ;         // Remove all Behaviors     [Self.animator removeallbehaviors];     // Add Behavior    [Self.animator Addbehavior:snap];

Other simulation behaviors don't show up.

iOS Development-Advanced article--uidynamic physics engine

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.