UIPushBehavior

{
    __weak IBOutlet UIImageView     *_boxImageView;
    
    UIDynamicAnimator               *_animator;
    UIPushBehavior                  *_push;
    
    // 是否第一次点按的标记
    BOOL                            _isFirstTap;
    // 第一次点按的点坐标
    CGPoint                         _firstPoint;
}
@end

@implementation PushViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [_boxImageView setTransform:CGAffineTransformMakeRotation(45)];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(110, 300, 20, 20)];
    view.backgroundColor = [UIColor blueColor];
    [self.view addSubview:view];
    
    _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
    
    UIDynamicItemBehavior *item = [[UIDynamicItemBehavior alloc] initWithItems:@[view]];
    item.elasticity = 0.8f;
    [_animator addBehavior:item];
    
    // 实例化一个推的行为
    _push = [[UIPushBehavior alloc] initWithItems:@[_boxImageView] mode:UIPushBehaviorModeInstantaneous];
    
    [_animator addBehavior:_push];
    
    // 实例化碰撞行为
    UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[_boxImageView, view]];
    collision.translatesReferenceBoundsIntoBoundary= YES;
    [_animator addBehavior:collision];
}

#pragma mark 点按手势
- (IBAction)tapGesture:(UITapGestureRecognizer *)sender
{
    _isFirstTap = !_isFirstTap;
    
    if (_isFirstTap) {
        _firstPoint = [sender locationInView:self.view];
        
        return;
    }
    
    // 取出第二个点的位置,计算两点间的距离和角度
    CGPoint p = [sender locationInView:self.view];
    
    // powf 是计算float数值的多少次方
    CGFloat xOffset = p.x - _firstPoint.x;
    CGFloat yOffset = p.y - _firstPoint.y;
    // 计算距离
    CGFloat dis = sqrtf(powf(xOffset, 2.0) + powf(yOffset, 2.0f));
    // 计算角度
    CGFloat angle = atan2(yOffset, xOffset);
    
    _push.angle = angle;
    _push.magnitude = dis / 30.0f;
    
    // 在使用单次推行为时,需要使用active激活该次推操作
    _push.active = YES;
}

@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值