在UIBezierPath上动画的UIImageView没有检测到碰撞

时间:2014-12-22 20:03:00

标签: objective-c collision-detection uibezierpath

UIImageView旅行了UIBezierPath

- (void)viewDidLoad {
    [super viewDidLoad];

    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(60, 60)];
    [path addLineToPoint:CGPointMake(70, 70)];
    [path addLineToPoint:CGPointMake(80, 120)];

    [self.thingy setImage:[UIImage imageNamed:@"titles.png"]];
    [self.thingy.layer setPosition:CGPointMake(60, 60)];
    [self.view.layer addSublayer:self.thingy.layer];

    CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    anim.path = path.CGPath;
    anim.rotationMode = kCAAnimationRotateAuto;
    anim.duration = 8.0;
    [self.thingy.layer addAnimation:anim forKey:@"move"];

    self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(tester)
                                                userInfo:nil
                                                 repeats:YES];
}

目标:我想检测thingy是否与barrier发生碰撞。这是tester

- (void) tester {
    NSLog(@"calling method");
    if (CGRectIntersectsRect(self.thingy.frame, self.barrier.frame)) {
        NSLog(@"collided");
    }
}

barrierthingy都是UIImageViews在头文件中声明为weaknonatomic

问题:tester每秒都会被调用,但当两个UIImageViews碰撞时,没有任何反应。尝试使这项工作有任何帮助吗?

1 个答案:

答案 0 :(得分:1)

由于thingy正在制作动画,因此您无法从其框架中获取准确的值。如果我没记错的话,一旦动画开始,视图将立即拥有动画结束时的最终帧。如果你想在它运动时测试它的框架,你必须测试这个图层的presentationLayer的框架。像这样:

- (void) tester {
    NSLog(@"calling method");

    if (CGRectIntersectsRect(((CALayer *)[self.thingy.layer presentationLayer]).frame, self.barrier.frame)) {
        NSLog(@"collided");
    }
}

注意:如果您的屏障也在运动中,您也必须使用其presentationLayer。