0

I move an instance of CCSprite in my Cocos2D-based iPhone game like this:

[mySprite runAction:[CCMoveBy actionWithDuration:1.0 
                                        position:ccp(10, 10)]];

How can I get a callback everytime the sprite moves?

I'd like to do something like this:

[self registerForCallbacksFrom:mySprite 
                      selector:@selector(spriteMovedOneStep)];

So spriteMovedOneStep would be called everytime mySprite moves. Would be nice to specify the frequency of the callback too so minimize CPU usage.

SundayMonday
  • 19,147
  • 29
  • 100
  • 154
  • 1
    Do you want the callback every frame while the sprite is moving, or once when the move ended? The former is a matter of setting "isMoving" in an ivar and process that in the normal update method. – CodeSmile Oct 13 '12 at 20:42
  • @LearnCocos2D I'd like the callback every frame (or every other frame). I've used `CCSequence` and `CCCallFunc` to handle the latter case you mentioned. Also I'm curious because I don't need the normal update method most of the time. Just for short bursts. So I suppose scheduling/unscheduling some selector could work. – SundayMonday Oct 13 '12 at 20:44

2 Answers2

1

One possible solution is to subclass CCMoveBy and call your callback from it's update method. You also can setup frequency and everything you want with this approach.

andrey.s
  • 789
  • 10
  • 28
1

If I get your question right you would like to have a method called at times when the Sprite is moving, correct ? How about scheduling an update method that performs what you want if a SpriteIsMoving BOOL is set to YES, I'm not sure on what your trying to achieve but this is my take on it.

Shachar
  • 1,110
  • 9
  • 22
  • You're understanding is correct and that's basically what I do. When the sprite starts moving I schedule a selector `handleMovingSprite`. When the sprite stops moving I unschedule the selector. To be safe I make sure the moving sprite exists before I use it (in the selector). – SundayMonday Oct 16 '12 at 15:50