[英]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.