2012-04-13 65 views
1

在我UIView,我创建了一个名为UIImageView的的TargetView,我已经将它设置为一系列动画制作:如何在动画时检测两个图像帧的相交?

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

我还创造了另一个名为UIImageView的shootView将移动到目标方向在手指轻扫时。它的运动也被实现为动画。在它的动画结束,检测相交用的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

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

一个解决方案可能是使用NSTimer为shootview的位置设置动画,并且每次位置变换都会进行碰撞检测。即

[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 
}