Question

I want to move a node and call a block after move done. But sometimes I need to move the node to another position while that node is moving (change destination).

I can't simply stop the previous action and start new one because than the callback will not be called and lead to inconsistent state.

id move = [CCMoveTo actionWithDuration:time position:pos];
id call = [CCCallBlock actionWithBlock:^{
// do something like clean up
}];
CCSequence *action = [CCSequence actions:move, call, nil];
action.tag = kMovingActionTag;
[node runAction:action];

I can get the action by CCSequence *action = (id)[node getActionByTag:kMovingActionTag]; but than the only thing I can do is stop it and lost the CCCallBlock action.


This is improved solution:

@interface CCMoveTo (SetEndPosition)

- (void)setEndPosition:(CGPoint)position;

@end


@implementation CCMoveTo (SetEndPosition)

- (void)setEndPosition:(CGPoint)position {
    CGPoint pos = [target_ position];
    CGFloat dis = ccpLength(delta_);
    CGFloat move = ccpDistance(endPosition_, pos);
    CGFloat percent = move / dis;

    endPosition_ = position;
    delta_ = ccpSub( endPosition_, pos);
    delta_.x /= percent;
    delta_.y /= percent;
    startPosition_ = ccpSub(endPosition_, delta_);
}

@end
Was it helpful?

Solution

You can add a setEndPosition method using category (warning: untested, let me know in comments if this doesn't work):

@interface CCMoveTo (SetEndPosition)

- (void)setEndPosition:(CGPoint)position;

@end


@implementation CCMoveTo (SetEndPosition)

- (void)setEndPosition:(CGPoint)position {
    endPosition_ = position;
    delta_ = ccpSub( endPosition_, startPosition_ );
}

@end

Then, modify the destination by calling [move setEndPosition:newPosition] (meaning you have to make the move variable accessible to the code portion which will modify the destination).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top