您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

【iOS】用 UIDynamic 打造逼真的物理碰撞動畫

編輯:iOS 開發綜合

一、需求

這次要實現的是一個帶有真實物理手感的碰撞動畫:一顆籃球從半空中落下,砸到地面後反彈,而不是像傳統動畫那樣靠人肉計算位移曲線。

二、為什麼選 UIDynamic

要在 UIKit 裡做出重力、碰撞、拋擲這類效果,UIDynamic 是最省力的入口。平時我們寫動畫,本質上是在關鍵幀之間做插值;而 UIDynamic 的思路完全不同——你只需要告訴系統「場景裡有哪些物體、它們受什麼力、彼此怎麼碰撞」,剩下的積分運算交給物理引擎,畫面自然就真實了。

在工程裡引入 UIKit 之後,從 Headers 目錄翻一遍就能找到幾個關鍵頭文件:

  • UIDynamicAnimator.h —— 物理動畫的「舞台」,負責驅動整個模擬過程
  • UIDynamicBehavior —— 所有物理行為的基類
  • UIDynamicItemBehavior —— 描述單個物件自身的物理屬性

既然要的是動畫,那麼入口毫無疑問是 UIDynamicAnimator。翻開它的頭文件註釋:

// When you initialize a dynamic animator with this method, you should only
// associate views with your behaviors.
// the behaviors (and their dynamic items) that you add to the animator employ
// the reference view's coordinate system.
- (instancetype)initWithReferenceView:(UIView *)view NS_DESIGNATED_INITIALIZER;

意思很直白:初始化時傳入一個「參考視圖」,之後所有行為裡的座標都基於這個視圖的座標系來計算。也就是說,animator 是容器,行為(behavior)才是內容。

那 behavior 又有哪些?繼續看 UIDynamicBehavior 的類註釋:

This parent class, UIDynamicBehavior, is inherited by the primitive dynamic
behavior classes UIAttachmentBehavior, UICollisionBehavior, UIGravityBehavior,
UIDynamicItemBehavior, UIPushBehavior, and UISnapBehavior.

蘋果把常用的物理行為都列在這裡了,中文對照如下:

  • UIGravityBehavior:重力行為,讓物件往一個方向持續加速
  • UICollisionBehavior:碰撞行為,處理物件之間以及物件與邊界之間的碰撞
  • UIAttachmentBehavior:附著行為,用「看不見的彈簧」把物件連到某個點或另一個物件上
  • UIPushBehavior:推力行為,給物件一個持續或瞬時的推力
  • UISnapBehavior:吸附行為,讓物件被「吸」到指定位置
  • UIDynamicItemBehavior:動態元素行為,用來配置彈性、摩擦、密度、線性/角速度等屬性

這些行為既可以單獨使用,也可以任意組合。比如重力加碰撞就是落體反彈,推力加碰撞就是撞球,附著加重力就是鐘擺。需求分析的思路走到這裡,答案已經浮出水面了。

三、實現步驟

需求場景裡其實只有兩個參與者:地面(floor)和籃球(basketBall)。下面的示例基於 6s 模擬器,地面 y 座標取 600。

1. 建立 animator

self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];

2. 關聯行為

初始化 animator 時必須綁定一個或多個行為,重力負責「往下掉」,碰撞負責「撞回來」:

NSArray *animatorObjects = @[self.imageV1];

self.gravityBehav = [[UIGravityBehavior alloc] initWithItems:animatorObjects];
self.colision = [[UICollisionBehavior alloc] initWithItems:animatorObjects];

3. 監聽碰撞(可選)

self.colision.collisionDelegate = self;

4. 設定碰撞邊界

用兩個點連成一條線,作為籃球不可穿越的地面:

[self.colision addBoundaryWithIdentifier:@"boundaryLine"
                               fromPoint:CGPointMake(0, 600)
                                 toPoint:CGPointMake(SCREENWITH, 600)];

5. 設定物理參數

彈性係數決定反彈高度,0 是完全不反彈,1 是完全彈性碰撞:

UIDynamicItemBehavior *itemBehavior = [[UIDynamicItemBehavior alloc] initWithItems:animatorObjects];
[itemBehavior setElasticity:0.5];

6. 把行為加進 animator

行為單獨存在是不會有任何效果的,必須交給 animator 統一調度:

[self.animator addBehavior:self.gravityBehav];
[self.animator addBehavior:self.colision];
[self.animator addBehavior:itemBehavior];

四、完整示範代碼

以下代碼僅用於演示功能,命名和結構並未刻意遵守工程規範:

#import "ViewController.h"

#define SCREENWITH  [UIScreen mainScreen].bounds.size.width
#define SCREENHEIGHT [UIScreen mainScreen].bounds.size.height

@interface ViewController () 

@property (nonatomic, strong) UIDynamicAnimator    *animator;
@property (nonatomic, strong) UIGravityBehavior    *gravityBehav;
@property (nonatomic, strong) UICollisionBehavior  *colision;
@property (nonatomic, strong) UIImageView          *imageV1;
@property (nonatomic, strong) UIImageView          *imageV2;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self jjCollisionBehav];
}

- (void)jjCollisionBehav {
    // 準備參與模擬的兩個物件
    [self jjCreateBall];
    [self jjCreateFloor];

    // 舞台
    self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];

    NSArray *animatorObjects = @[self.imageV1];

    // 重力 + 碰撞
    self.gravityBehav = [[UIGravityBehavior alloc] initWithItems:animatorObjects];
    self.colision = [[UICollisionBehavior alloc] initWithItems:animatorObjects];
    self.colision.collisionDelegate = self;

    // 地面邊界
    [self.colision addBoundaryWithIdentifier:@"boundaryLine"
                                   fromPoint:CGPointMake(0, 600)
                                     toPoint:CGPointMake(SCREENWITH, 600)];

    // 彈性
    UIDynamicItemBehavior *itemBehavior = [[UIDynamicItemBehavior alloc] initWithItems:animatorObjects];
    [itemBehavior setElasticity:0.5];

    // 行為入場
    [self.animator addBehavior:self.gravityBehav];
    [self.animator addBehavior:self.colision];
    [self.animator addBehavior:itemBehavior];
}

#pragma mark - UICollisionBehaviorDelegate

- (void)collisionBehavior:(UICollisionBehavior *)behavior
        endedContactForItem:(id)item
     withBoundaryIdentifier:(id)identifier {
    NSLog(@"collision item = %@", item);

    NSString *identifierStr = [NSString stringWithFormat:@"%@", identifier];
    if ([identifierStr isEqualToString:@"boundaryLine"]) {
        // 落地瞬間給地面一個視覺反饋
        [UIView animateWithDuration:2 animations:^{
            [self.imageV2 setBackgroundColor:[UIColor grayColor]];
        }];
    }
}

#pragma mark - 建立物件

- (void)jjCreateBall {
    _imageV1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"basketBall"]];
    _imageV1.frame = CGRectMake(100, 100, 60, 60);
    [self.view addSubview:_imageV1];
}

- (void)jjCreateFloor {
    _imageV2 = [[UIImageView alloc] init];
    [_imageV2 setBackgroundColor:[UIColor grayColor]];
    _imageV2.frame = CGRectMake(0, 600, SCREENWITH, SCREENHEIGHT - 400);
    [self.view addSubview:_imageV2];
}

@end

小結

UIDynamic 的價值在於把「物理」這件事交還給系統。真實項目裡,除了本例的重力加碰撞,我們還常用 UIPushBehavior 做下拉刷新的小球動畫、用 UISnapBehavior 做拖拽吸附,或者用 UIAttachmentBehavior 模擬橡皮筋。把行為按需組合,往往幾十行代碼就能替換掉一大段核心動畫,效果還更自然。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved