views:

33

answers:

2

Hi,

I am looking for some way to make 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 ...

A: 

Have you considered an actual physics engine? Bullet, for example, is pretty awesome.

Kalle
I am planning to make a game like "labyrinth" ... so I would need collision detection and some other features. Would a physics engine be necessary ? Can this be achieved by normal coding in objective C ? If its difficult, can you suggest me some free 2D physics engine ?
tuttu47
+1  A: 

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.

Brad Larson