Smoothly drag a Sprite in cocos2d - iPhone

10,587

Solution 1

Probably a little bit late but I was searching for a similar thing. I found this great Tutorial which explained everything: http://www.raywenderlich.com/2343/how-to-drag-and-drop-sprites-with-cocos2d

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {       
    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];

    CGPoint oldTouchLocation = [touch previousLocationInView:touch.view];
    oldTouchLocation = [[CCDirector sharedDirector] convertToGL:oldTouchLocation];
    oldTouchLocation = [self convertToNodeSpace:oldTouchLocation];

    CGPoint translation = ccpSub(touchLocation, oldTouchLocation);    
    CGPoint newPos = ccpAdd(mySpriteToMove.position, translation);
    mySpriteToMove.position = newPos;
}

Solution 2

I had this same issue with my game. Dragging operations appeared jerky. I believe the reason is that touch events aren't generated fast enough to give a smooth appearance.

To solve the problem I smoothed the motion out by running an action on the sprite toward the desired location, instead of setting the position immediately.

Share:
10,587
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I have implemented a drag on a sprite object as follows..

    -(BOOL)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    
    UITouch * touch = [touches anyObject];
    CGPoint location = [[Director sharedDirector] convertCoordinate: [touch locationInView:touch.view]];    
    [diskSprite setPosition:ccp(location.x , location.y )];
    return kEventHandled;
    }
    

    but this dragging is not smooth..... when i drag fast with my thumb the object left from the path.

    Thanks