简体   繁体   English

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

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

I have a simple game that I'm starting to make that has a ball bouncing around and I want the user to be able to drag a paddle around and hit the ball. 我有一个即将开始制作的简单游戏,其中有一个球在弹跳,我希望用户能够拖动球拍并击中球。 The ball is bouncing around perfectly well, but the paddle behavior isn't working properly. 球弹跳得很好,但是桨的行为无法正常进行。

In the function start the paddle is created and then an attachment behavior is setup and a PanGestureRecogniser is declared: 在函数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];

The panGestureRecognizer looks like this: 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];
    } 
}

I can move the paddle around but it doesn't follow my finger, and the collisions with the ball don't look like they did before I added the ability to move the paddle. 我可以移动球拍,但是它不会跟随我的手指,并且与球的碰撞看起来不像在添加球拍功能之前那样。 I'd be grateful for some help with this. 感谢您的帮助。

Don't add and remove the behavior with each gesture, just add it once, then move the anchorPoint . 不要在每个手势上添加和删除行为,只需添加一次,然后移动anchorPoint The animation will need some time to run after your gesture recognizer hits UIGestureRecognizerStateEnded . 手势识别器击中UIGestureRecognizerStateEnded之后,动画将需要一些时间才能运行。

If you really want to remove the behavior, implement UIDynamicAnimatorDelegate and wait for the dynamicAnimatorDidPause message. 如果您确实要删除该行为,请实现UIDynamicAnimatorDelegate并等待dynamicAnimatorDidPause消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM