I'm trying to move a sprite around at a constant speed. The following code snippet accomplishes this:
float speed = 200.0;
CGPoint startPosition = [sprite position];
CGPoint endPosition = convertedPoint;
float newDuration = ccpDistance(startPosition, endPosition) / speed;
[sprite runAction: [MoveTo actionWithDuration:newDuration position:convertedPoint]];
However, I was thinking of a way to extend Cocos2d to do this, I was trying to create a custom init function for MoveTo. So I created an Objective C category to extend MoveTo:
@implementation MoveTo (speed)
+(id) actionWithSpeed: (float) t position: (CGPoint) p;
{
return [[[self alloc] initWithSpeed:t position:p ] autorelease];
}
-(id) initWithSpeed: (float) t position: (CGPoint) p
{
startPosition = [(CocosNode*)target position];
endPosition = p;
float newDuration = ccpDistance(startPosition, endPosition) / t;
if( !(self=[super initWithDuration: newDuration]) )
return nil;
return self;
}
@end
Sadly, this does not work, the speed of the action seems to vary unpredictably. Can anyone point me in the right direction?
-CJL