在我的UIView中,我创建了一个名为targetView的UIImageView,我将其设置为一系列动画:
[UIView animateWithDuration:1.0
animations:^{self.targetView.center = CGPointMake(220,20);}
completion:^(BOOL finished){
//another animation will begin;
}];
我还创建了另一个名为shootView的UIImageView,它将在手指滑动时移动到目标方向。它的运动也作为动画实现。在其动画结束时,检测与目标视图的相交:
[UIView animateWithDuration:1.0
animations:^{
self.shootView.center = CGPointMake(destX, destY);}
completion:^(BOOL finished){
if (CGRectIntersectsRect(self.targetView.frame, self.shootView.frame)) {
//do something
}];
现在有一个问题:仅当目标视图到达当前动画的终点并且 shootView 恰好在那里时,相交命令才能正常工作。当 targetView 在动画中间的某处移动时,即使从视觉上看很明显两帧相交,也无法检测到相交。
这种方法可能很棘手,因为您只能在 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
}