I've been playing around with the idea of sprites following pre-defined paths. I really just want the ability to move along arbitrary curves... I seem to remember there being a spline or bezier action in the python version of cocos2d, but I'm not sure if it was ever ported to this iPhone branch. I might try to implement it myself later, but just as a test I made the following action:
@implementation TraversePathAction
+(id) actionWithDuration: (ccTime) t path: (NSArray*) path {
return [[[self alloc] initWithDuration:t path:path] autorelease];
}
-(id) initWithDuration: (ccTime) t path: (NSArray*) path {
self = [super initWithDuration:t];
if (self != nil) {
pathArray = [path retain];
}
return self;
}
-(id) copyWithZone: (NSZone *)zone {
Action *copy = [[[self class] allocWithZone:zone] initWithDuration:[self duration] path:pathArray];
return copy;
}
-(void) start {
[super start];
}
-(void) update: (ccTime) t {
int pathPointCount = [pathArray count];
int index = (int) ((((float)pathPointCount-1)+0.5f)*t);
NSValue *value = [pathArray objectAtIndex:index];
CGPoint movePoint = [value CGPointValue];
//todo: interpolation
[target setPosition:movePoint];
}
-(void) dealloc {
[pathArray release];
[super dealloc];
}
@end
This works well if you set up the path array with CGPoint objects (contained in NSValue objects) representing a curve, but it needs a significant point resolution to appear smooth. It could be improved (as I noted in the todo) by using interpolation... moving between array points based on the remaining time after integer index truncation.
Have you guys implemented something similar or better?