Search code examples
ioscocos2d-iphoneccsprite

Animation in touchMoved method not working


I have a animation method that moves a CCSprite to a certain location based on the users touch within the touchMoved method.

 -(void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event{

//Some misc code then ...

CGPoint newposition = (ccpAdd(spritePosition, moveVec));
[sprite runAction:[CCActionMoveTo actionWithDuration:0.3 position:newposition]];

When I run this method it moves the sprite around all over the screen and not to the CGPoint NewPosition.

However if I change it to not include the animation

sprite.position = newposition;

It works.

What am I doing wrong?


Solution

  • You probably want to put your code in -(void) touchEnded:(UITouch *)touch withEvent:(UIEvent *)event method. touchMoved is called as the touch moves and therefore is called more than once which means that the runAction method on your sprite is being called more than once for different newPosition values which is firing off different runAction commands at nearly the same time resulting in unexpected behaviour.

    Though, runAction method checks if the action is already running . However in your case a new instance of CCActionMoveTo is being created on every call , hence that check is not protecting you. I believe shifting your touchMoved code to touchEnded should solve the issue.

    EDIT :

    If you cannot move the code to touchEnded , an alternative could be to use a boolean flag and enfore a sprite animation check yourself.

    use a global BOOL isSpriteAnimating = NO;

    and in your touchMoved function

    if(!isSpriteAnimating){
        isSpriteAnimating = YES;
        [sprite runAction:[CCActionSequence actions:[CCActionMoveTo actionWithDuration:0.3 position:newposition],[CCActionCallBlock actionWithBlock:^{
        isSpriteAnimating = NO; 
        }],nil]];
    }