簡體   English   中英

使用UIDynamicAnimator的平移手勢拖動UIView的正確方法

[英]Correct way to drag a UIView around with a pan gesture with a UIDynamicAnimator

我有一個即將開始制作的簡單游戲,其中有一個球在彈跳,我希望用戶能夠拖動球拍並擊中球。 球彈跳得很好,但是槳的行為無法正常進行。

在函數start中創建槳,然后設置附件行為並聲明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];
    } 
}

我可以移動球拍,但是它不會跟隨我的手指,並且與球的碰撞看起來不像在添加球拍功能之前那樣。 感謝您的幫助。

不要在每個手勢上添加和刪除行為,只需添加一次,然后移動anchorPoint 手勢識別器擊中UIGestureRecognizerStateEnded之后,動畫將需要一些時間才能運行。

如果您確實要刪除該行為,請實現UIDynamicAnimatorDelegate並等待dynamicAnimatorDidPause消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM