I need to do the following: a sprite is moved to a position, when the sprite goes to this position, I need to execute the reverse action.
For testing in this example I just print “ok” when I reach that position, avoiding so to over-release the action and to risk some exception.
-(id) init
{
if( (self=[super init]))
{
soldier=[CCSprite spriteWithFile: @"soldier.gif"];
soldier.position= CGPointMake(250, 250);
[self addChild: soldier];
CGPoint position=[soldier convertToNodeSpace: CGPointZero];
CCMoveTo* move=[CCMoveBy actionWithDuration: 2 position: position];
[move retain];
[soldier addObserver: self forKeyPath: @"position" options: NSKeyValueObservingOptionNew context: (void*)move];
[soldier runAction: move];
}
return self;
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
CGPoint position= [self convertToNodeSpace: soldier.position];
if(CGPointEqualToPoint(position, CGPointZero));
{
NSLog(@"ok");
}
}
The problem is that it prints “ok” a lot of times, it should print it only a time, why?
EDIT
I removed the extra ‘;’ :
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
CGPoint position= [self convertToNodeSpace: soldier.position]; // breakpoint here
if(CGPointEqualToPoint(position, CGPointZero))
{
NSLog(@"ok");
}
}
Now it never prints “ok”.In the breakpoint I print position and the last value is (47,47), it never reaches (0,0).
I wouldn’t use KVO/KVC with cocos2d for the simple reason that cocos2d is not KVC/KVO compliant. A Cocos2D class’ properties might change without you ever getting a notification.
I don’t know if this is the problem here or not, but there’s a good chance if you continue with KVC/KVO you’ll eventually run into problems.