如何在动画时检测两个图像帧的交叉?

时间:2012-04-13 20:20:23

标签: xcode animation uiview uiimageview intersect

在我的UIView中,我创建了一个名为 targetView 的UIImageView,我将其设置为一系列动画:

[UIView animateWithDuration:1.0
                 animations:^{self.targetView.center = CGPointMake(220,20);}
                 completion:^(BOOL finished){
                                             //another animation will begin;
                                            }];

我还创建了另一个名为 shootView 的UIImageView,它会在手指滑动时移动到目标方向。它的运动也被实现为动画。在动画结束时,检测与targetView的交叉:

[UIView animateWithDuration:1.0
                 animations:^{
                 self.shootView.center = CGPointMake(destX, destY);}
                 completion:^(BOOL finished){
                            if (CGRectIntersectsRect(self.targetView.frame, self.shootView.frame)) {
                            //do something
                             }];

现在有一个问题:如果targetView已经到达当前动画的终点并且shootView碰巧在那里,则交叉命令才能正常工作。当targetView在动画中间的某个位置移动时,即使在视觉上两个帧相交的非常明显,也无法检测到交叉。

1 个答案:

答案 0 :(得分:1)

这种方法可能很棘手,因为你只能在UIView动画的开始和结束时获得回调。在您的示例中,仅在动画完成后才调用CGRectIntersectRect方法。

一种解决方案可能是使用NSTimer来对拍摄视图的位置进行动画处理,并且每次更改位置都会进行碰撞检测。即

[NSTimer timerWithTimeInterval: 0.03 target: self selector: @selector(timerTicked:) userInfo: nil repeats: YES];

-(void) timerTicked: (NSTimer*) timer {

  // do move
  // check for colisions
  // optional invalidation of timer
}