Search code examples
iphoneobjective-ccocos2d-iphoneccsprite

Drag sprite in cocos2d for the iPhone - with a max velocity


I'm trying to make a game where the user is supposed to drag a sprite up and down on the screen, avoiding incoming obstacles. The last answer here helped me to drag the sprite around on the screen, but I want to set a maximum speed the sprite can be moved (and hopefully with a natural-looking acceleration/deceleration), so it doesn't get too easy to avoid the objects.

Does anybody know how I can modify the code to achieve this, or is there another way to to it?

Thanks :)


Solution

  • You'll need to maintain a CGPoint destinationPosition variable which is the location of your finger and use an update loop to modify it's position:

    -(void) update:(ccTime) dt
    {
        CGPoint currentPosition = draggableObject.position.x;
        if (destination.x != currentPosition.x)
        {
            currentPosition.x += (destination.x - currentPosition.x) / 5.0f; // This 5.0f is how fast you want the object to move to it's destination
        }
        if (destination.y != currentPosition.y)
        {
            currentPosition.y += (destination.y - currentPosition.y) / 5.0f;
        }
        draggableObject.postion = currentPosition;
    }
    

    In the ifs, you might want to check if the objects are close to each other, rather than exactly the same number to allow for rounding errors.