iOS7 UIKit动力学-碰撞特性UICollisionBehavior 下

上文讲到了为window加一个边界。实现碰撞的效果,接下来我们将提到一个托付方法:

- (void)collisionBehavior:(UICollisionBehavior *)behavior 

beganContactForItem:(id<UIDynamicItem>)item 

withBoundaryIdentifier:(id<NSCopying>)identifier a

tPoint:(CGPoint)p;

这种方法是在边界发生碰撞的时候才去运行的

UICollisionBehavior 这个和tableview的托付方法一样理解。item是碰撞的对象。identifier为对象加入定义,p为发生碰撞的位置。

怎样实现碰撞这种方法呢,例如以下:

引用<UICollisionBehaviorDelegate>这个托付,然后把_ground对象的托付给当前这个viewController。方法例如以下:

.h

#import <UIKit/UIKit.h>
//new
@interface ViewController : UIViewController<UICollisionBehaviorDelegate>
{
    UIDynamicAnimator * _animator;
    UIGravityBehavior * _gravity;
    UICollisionBehavior * _ground;
}
@end

.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView * apple = [[UIView alloc] initWithFrame:CGRectMake(40,40, 40, 40)];
    apple.backgroundColor = [UIColor redColor];
    [self.view addSubview:apple];
    
    _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
    _gravity = [[UIGravityBehavior alloc] initWithItems:@[apple]];
    [_animator addBehavior:_gravity];
    
    _ground = [[UICollisionBehavior alloc] initWithItems:@[apple]];
    _ground.translatesReferenceBoundsIntoBoundary = YES;
    [_animator addBehavior:_ground];
    //new
    _ground.collisionDelegate = self;
}

设置_ground.collisionDelegate为试图控制器。之后当界面在发生碰撞,就能够调用一開始所说的托付方法了。

.m   仍在viewController中

- (void)collisionBehavior:(UICollisionBehavior *)behavior beganContactForItem:(id<UIDynamicItem>)item withBoundaryIdentifier:(id<NSCopying>)identifier atPoint:(CGPoint)p{
    NSLog(@"好疼,我撞在%f,%f。%@",p.x,p.y,identifier);
}

小知识补充:

UICollisionBehavior的属性中有一个叫做action的属性

@property (nonatomic,copy)void (^action)(void);

非常明显的能看出来。这是一个block的结构,无參数。无返回值。

    _ground.action = ^{
        NSLog(@"%@, %@",
              NSStringFromCGAffineTransform(apple.transform), NSStringFromCGPoint(apple.center));
    };

你能够通过这个Block来获得某个有动力学属性的对象的各种执行效果,在这里你能够看到动态引擎使用的组合变换和帧偏移位置视图依据主要的物理模型。而动态的确切值适用于这些属性可能是不感兴趣,重要的是要知道他们被应用。因此,假设您以编程方式更改帧或改变对象的属性,你能够预期,这些值将被覆盖。这意味着您不能使用转换扩展对象尽管是动态的控制下。

动态行为使用术语的方法签名的物品而不是视图。


    [_ground addBoundaryWithIdentifier:@"apple" fromPoint:CGPointMake(10, 10) toPoint:CGPointMake(320, 568)];//通过这个能够设置重力加速度的方向

通过这种方法,你能够设置视图运动的起始位置和终点位置,这里的@"apple"能够在托付方法中,被提取出来的。



执行一下。看看效果吧。

点击关注我,很多其它精彩内容!!!

群号:336146073






原文地址:https://www.cnblogs.com/yxwkf/p/5227800.html