Making an image follow a pre defined path in iPhone?
I am looking for some way to ma开发者_运维技巧ke an image (a ball) move along a predefined path in iPhone. My intention is to create a ball movement similar to the labyrinth movement. I understand there is a way to create paths programmatically using CGPath. But I believe it is difficult to create complex paths. Is there a better and easier way to create a path out of an image (which will look or represent a path) and make the image (ball) movement constrained in this path ?
Thanx in advance for help ...
It's not really that hard to create an animation for moving an object along a path. For example, the following code will animate along a specific Bezier curve:
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
pathAnimation.duration = 1.0f;
pathAnimation.calculationMode = kCAAnimationPaced;
CGPoint currentPosition = viewToAnimate.layer.position;
CGPoint endPoint = CGPointMake(currentPosition.x + 100.0f, currentPosition.y - 50.0f);
CGMutablePathRef curvedPath = CGPathCreateMutable();
CGPathMoveToPoint(curvedPath, NULL, currentPosition.x, currentPosition.y);
CGPathAddCurveToPoint(curvedPath, NULL, endPoint.x, currentPosition.y, endPoint.x, currentPosition.y, endPoint.x, endPoint.y);
pathAnimation.path = curvedPath;
CGPathRelease(curvedPath);
pathAnimation.fillMode = kCAFillModeForwards;
pathAnimation.removedOnCompletion = NO;
[viewToAnimate.layer addAnimation:pathAnimation forKey:@"animateMovementUsingPath"];
The center section of that code is where the path is defined. In this case, I start drawing at currentPosition
, then add a curve which ends at endPoint
. The control points for this curve are (endPoint.x, currentPosition.y)
and (endPoint.x, currentPosition.y)
.
It will be far easier to define a vector curve in this fashion and let Core Animation handle all the tweening for you than to manage all of the animation yourself.
Have you considered an actual physics engine? Bullet, for example, is pretty awesome.
精彩评论