使用UIDynamicAnimator以平移手势拖动UIView的正确方法

时间:2014-03-15 17:49:54

标签: ios objective-c uiview

我有一个简单的游戏,我开始制作有一个球弹跳,我希望用户能够拖动球拍并击球。球很好地弹跳,但桨的行为不能正常工作。

在函数start中创建了paddle,然后设置了附件行为并声明了PanGestureRecogniser

self.attach = [[UIAttachmentBehavior alloc] initWithItem:self.paddle attachedToAnchor:self.paddle.center];
self.attach.damping = 1.0;

SEL drag_sel = NSSelectorFromString(@"drag:");

self.paddle.userInteractionEnabled = YES;
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:drag_sel];

[self.paddle addGestureRecognizer:panGestureRecognizer];

panGestureRecognizer看起来像这样:

- (void)drag :(UIPanGestureRecognizer*)pan {

    CGPoint p = [pan translationInView:self.hockeyView];
    NSLog(@"%f, %f", p.x, p.y);

    UIView *targetView = pan.view;
    self.attach.anchorPoint = p;

    if (pan.state == UIGestureRecognizerStateBegan){
        [self.animator addBehavior:self.attach];
    }
    else if (pan.state == UIGestureRecognizerStateEnded){
        [self.animator removeBehavior:self.attach];
    } 
}

我可以移动球拍,但它不会跟随我的手指,并且在我添加移动球拍的能力之前,与球的碰撞看起来不像他们所做的那样。我很感激能帮到你。

1 个答案:

答案 0 :(得分:0)

不要添加和删除每个手势的行为,只需添加一次,然后移动anchorPoint。在手势识别器点击UIGestureRecognizerStateEnded后,动画需要一段时间才能运行。

如果您确实要删除该行为,请实施UIDynamicAnimatorDelegate并等待dynamicAnimatorDidPause消息。