[心得] 一个图片围绕一个圆心做圆运动

-(void)step:(ccTime)dt
{
    if (rotate == 360) {
        rotate = 0;
    }
    rotate += 5;
    float fradian = rotate * PI / 180;
    NSLog(@"%f  %f",rotate,fradian);
    id ac0 = [CCMoveTo actionWithDuration:0.01
                                 position:ccp(centerx + radius * sinf(fradian),
                                              centery + radius * cosf(fradian))];
    id ac1 = [CCRotateTo actionWithDuration:0.01 angle:(int)(rotate)];
    [sparrowhead runAction:[CCSpawn actions:ac0,ac1,nil]];
}

 

根据算法,写成一个cocos2d的action,应该比step效率高

/** Round circle a CCNode object clockwise a number of degrees by modiying it's rotation attribute.
*/
@interface CCRoundBy : CCActionInterval <NSCopying>
{
    BOOL turn;// Forward or Reverse round
    float startAngle;// default
    float radius;// Round circle radius
    CGPoint center;// Round circle center point
}
/** creates the action */
+(id) actionWithDuration:(ccTime)duration turn:(BOOL)a center:(CGPoint)point radius:(float)r;
/** initializes the action */
-(id) initWithDuration:(ccTime)duration turn:(BOOL)a center:(CGPoint)point radius:(float)r;
@end

 

//
// CCRoundBy
//
#pragma mark -
#pragma mark CCRoundBy

@implementation CCRoundBy
+(id) actionWithDuration: (ccTime) t turn:(BOOL) a center:(CGPoint)point radius:(float)r
{    
    return [[[self alloc] initWithDuration:t turn:a center:point radius:r] autorelease];
}

-(id) initWithDuration: (ccTime) t turn:(BOOL) a center:(CGPoint)point radius:(float)r
{
    if( (self=[super initWithDuration: t]) ) {
        turn = a;
        radius = r;
        center = point;
    }
    return self;
}

-(id) copyWithZone: (NSZone*) zone
{
    CCAction *copy = [[[self class] allocWithZone: zone] initWithDuration: [self duration] turn: turn center:center radius:radius];
    return copy;
}

-(void) startWithTarget:(id)aTarget
{
    [super startWithTarget:aTarget];
    startAngle = [target_ rotation];
    if (turn) {
        ((CCNode *)target_).position = ccpAdd(center, ccp(-radius, 0));
    }
    else {
        ((CCNode *)target_).position = ccpAdd(center, ccp(radius, 0));
    }    
}

-(void) update: (ccTime) t
{    
    // XXX: shall I add % 360
    float rotate =  (startAngle + 360.0f * t );
    if (turn) {
        rotate *= -1;
    }
    [target_ setRotation:rotate];
    
    float fradian = rotate * M_PI / 180.0f;
    CGPoint pos = ccp(center.x + radius * sinf(fradian),
                      center.y + radius * cosf(fradian));
    [target_ setPosition: pos];
}

-(CCActionInterval*) reverse
{    
    BOOL result = !turn;
    return [[self class] actionWithDuration:duration_ turn:result center:center radius:radius];
}

@end

posted on 2012-04-24 12:03  甲骨魚  阅读(374)  评论(0编辑  收藏  举报

导航