4
votes

I have an view-based iPhone app. Currently there is a small image in the top left hand corner of the screen. When the user taps the screen the image is animated using a CAKeyframeAnimation along a curvy path to the lower right hand corner of the screen.

Now I want to change the app so instead of animating on the tap event, the user can drag the image along the animation path. Basically when the user drags downward of rightward the animation steps forward, when the user drags upward or leftward the animation steps backward. On the touch ended event I want the image to continue to animate along the path in the direction of the drag.

I know how to read the drag event, but I don't know to start/stop/resume the animation or skip to a specific stage in the animation. It seems like I need to start over and use something other than CAKeyframeAnimation. If that is so, how should I start over?

Thanks so much!

2
In the end I re-wrote the animation as a function, so I could swap the input between time and and drag position. Time and drag position are scalar and scaled to match appropriately.Sam Goldman

2 Answers

1
votes

Unfortunately, there's no way to set a CAAnimation to start midway through.

You'll need to manually move your image along the path as the user drags, then create a new CAAnimation with the remaining path once the user is done dragging.

0
votes

Mark F is correct. I had a similar issue whilst working on a game. I wanted to restart the animations from exactly the point they were paused.

The simplest solution I could come up with was to capture the start time:

    mStartTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];

Then, when the animation is stopped, get the stop time and calculate an offset:

    CFTimeInterval stopTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];;
    mTimeOffset += stopTime - mStartTime;

Using the mTimeOffset, I'd calculate a different set of key times:

- (NSArray *)keyTimesWithOffsetTime:(CFTimeInterval)offsetTime;

Based on that, I'd get a different start frame for the animation. By "frame" I mean whatever segment of the key frame animation.

It's a bit of a pain to do but it does work. I'd be very interested to know how games using cocos2d handle pausing and resuming. There has to be an easier way.

Regarding an animation along a path, it seems that you have that going ok. If not, have a look at this tutorial:

Core Animation: Paths