Detecting collision, during a CAKeyFrameAnimation

2019-05-28 18:50发布

Is it possible to detect the collision of two UIImageViews while one is travelling along a path during a CAKeyFrameAnimation?

If so how is this done, I have tried multiple methods including checking both the CGRects for collision during the animation - but can't find a suitable method for performing a method during a CAKeyFrameAnimation and trying to detect collision of the path and the UIImageView.

1条回答
相关推荐>>
2楼-- · 2019-05-28 19:31

You need to get the properties from the presentation layer. It will have the best approximation of information that exists during animation. Access it by

view.layer.presentationLayer

Look at the documentation for CALayer/presentationLayer for more details.

When you want to check for collisions, you would grab the presentationLayer of each object, then access whatever properties you want to test for collision. The exact way to check would depend on which type of layer, and whether you wanted simple hitTest-ing or depth checking. Only you know when and what type of collisions you want to look for.

However, to access the properties of an object while it is animating, you need the presentationLayer.

EDIT

You can make these check whenever you want. You can do it in the context of another action, or with an NSTimer to do it at some interval. You can even use CADisplayLink, which while hook you into the animation timer itself.

If you use CADisplayLink, I suggest setting frameInterval at the highest value possible, and still do what you want, so as to not impact performance.

    timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(checkForCollisions)];
    // Callback is for every frame, which is 60 times per second.
    // Only callback every 6 frames (which is ten times per second)
    timer.frameInterval = 6;
    [timer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

Don't forget to invalidate the timer when you are done.

查看更多
登录 后发表回答