Tutorial :Animate object along a drawn path?



Question:

I recently downloaded the sample application, GLPaint from apple. This app showed me how to implement drawing, but now I would like to animate a image over the drawn lines. Similarly to how the application "Flight Control" works, I would like to be able to draw a path for an image and then have the image animate over this path.

any ideas?


Solution:1

you could create your path

CGMutablePathRef thePath = CGPathCreateMutable();  

and then in the touchesBegan and touchesMoved add to your path

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    UITouch *touch = [touches anyObject];    if(touch){      CGPoint tapPoint = [touch locationInView: self.view];      CGPathMoveToPoint(thePath, NULL,tapPoint.x,tapPoint.y);        }  }  - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{    UITouch *touch = [touches anyObject];    if(touch){      CGPoint tapPoint = [touch locationInView: self.view];      CGPathAddLineToPoint(thePath, NULL,tapPoint.x,tapPoint.y);    }  }  

and on touchedEnded, as Joshua said, create a CAKeyframeAnimation and set its path to thePath and set the other properties of your animation (duration, etc) and apply it to your object


Solution:2

Look at CAKeyframeAnimation, this allows you to set a path (which is a CGPathRef) for the animation to run along.


Solution:3

Based on code from AtomRiot, I created a simple project on my blog. See this post, also posted a short video showing the result.

However when the animation ends, the image will somehow repositioned back to (0,0), so might need to add extra code to reset the image location after animation finished.

Plus, found that you can't change the animation once it started, have to wait for it to end before you can change it.

Hope this helps!


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »