cocos2d-iphonespriteuibezierpathccspritecgpath

Cocos2d and iOS: how to use UIBezierPath to animate CCSprite movements?


I have found several post that teach how to use UIBezierPaths with CoreAnimation. This works because CAKeyframeAnimation objects have a property called path that is of type CGPath and also UIBezierPaths objects have a CGPath property.

I am wondering how I could get a CCSprite to move following a CGPath.

In CGPath there is a function CGPathGetCurrentPoint that will help me getting the current point in a path but I couldn't find something like "move to next point".

My pseudocode would work like this:

Create a CCSprite subclass with a UIBezierPaths property
Initialize the UIBezierPaths instance

Allocate the CCSprite subclass in a layer
schedule updates
In update method
     Reposition the CCSprite sublcass instance by getting the CGPathGetCurrentPoint to CGPathGetCurrentPoint
     Move the path forward by calling "move to next point"

Any idea if this would work? Is this an effective approach?


Solution

  • Not sure what you are trying to do, but this is how I move some sprite along bezier paths in Cocos2D:

    - (CCBezierTo*)bezierMoveTo:(CGPoint)destination node:(CCNode*)node duration:(float)d {
    
     static ccBezierConfig bzPaths[5] = {
        {{1050, 900}, {1200, 1400}, {1100, 900}},
        {{1100, 750}, {1300, 1550}, {1650, 500}},
        {{800, 850}, {500, 1100}, {400, 700}},
        {{700, 700}, {1500, 1200}, {400, 900}},
        {{900, 650}, {100, 900}, {900, 400}}
     };
     ccBezierConfig bezierOne;
     bezierOne = bzPaths[PATH_INDEX];
     return [CCBezierTo actionWithDuration:d bezier:bezierOne];
    }
    

    The returned action can be then run on a sprite. In my case, I have a set of static paths, and I choose one at random. In your case, it seems you would like to store the path within your custom sprite. Apart from that, everything should work.

    If you want to build more complex paths, simply use a sequence of ccBezierConfig and CCBezierBy.