CCNodeのカテゴリで、他のCCNodeをゆったり追うSoftFollowというのを作ってみた
要件
- CCNodeが、CCNodeを追って欲しい
- 自動追尾だけど、自然な感じで追って欲しい
- 指定したい項目は、対象Node、 引っ張られる強さ、対象との距離
- 気軽に使いたい
ということで、CCNodeのカテゴリで CCNode+SoftFolloというのを作った。
CCDelayを継承してActionとして作ってもよかったかも?
あんまり綺麗にかけなかったので、改善案求む。
CCNode+SoftFollow.h
#import "CCNode.h" @interface CCNode (SoftFollow) - (void)followTo:(CCNode *)targetNode strength:(float)strength; - (void)followTo:(CCNode *)tarNodgete strength:(float)strength distance:(float)distance; @end
CCNode+SoftFollow.m
#import "CCNode+SoftFollow.h" #import "CCActionInstant.h" #import "CCActionInterval.h" #import "CGPointExtension.h" @implementation CCNode (SoftFollow) - (void)followTo:(CCNode *)targetNode strength:(float)strength { [self followTo:targetNode strength:strength distance:0.0f]; } - (void)followTo:(CCNode *)targetNode strength:(float)strength distance:(float)distance { CCCallBlockN *follow = [CCCallBlockN actionWithBlock:^(CCNode *node) { float distX = targetNode.position.x - node.position.x; float distY = targetNode.position.y - node.position.y; float dist = sqrtf(distX*distX + distY*distY); if (dist > distance) { node.position = ccpAdd(self.position, ccp(distX*strength,distY*strength)); } }]; CCSequence *seq = [CCSequence actions:[CCDelayTime actionWithDuration:0.0f],follow, nil]; CCRepeatForever *repeat = [CCRepeatForever actionWithAction:seq]; [self runAction:repeat]; }
scheduleにするのがなんとなく嫌で、CCRepeatForeverするための苦肉の策が、
CCDelayTimeを挟み込んだSequenceとすること…うーん。
問題は止められないということ
とりあえず, repeatにタグつけて、 [self stopActionByTag: タグ] ってやる関数を作れば止まるけどダサい。
追記 2012/11/27 19:33
kmVec2を使って書きなおしてみました。ついでにstopFollowも仮実装。
CCNodeのカテゴリで、他のCCNodeをゆったり追うSoftFollowというのを作ってみた その2 - 追記2/26 - taoru's memo