Search code examples
performancecocos2d-iphonesprite

Cocos2d Sprite Movement Speed


I have a class which creates a sprite at a random point on the screen, this sprite then moves to the center of the screen.

How can I make it so that it always travels at the same speed?

obviously

CCMoveTo* move = [CCMoveTo actionWithDuration:5 position: ccp(screenWidth/2, screenHeight/2)];

Will always mean the duration is 5 seconds regardless of the distance. But I want the speed to be constant if its travelling 50 pixels or 500 pixels.

Any Help much appreciated


Solution

  • Calculate the duration from the distance to the center.

    duration = distance / rate;
    

    Say that moving 50 pixels in 5 seconds is okay. Then your rate is 10 pixels/second.

    rate = 10;
    

    If your sprite is at (x,y) then distance is by the pythagorean theorem

    dx = x - screenWidth / 2;
    dy = y - screenHeight / 2;
    distance = sqrt(dx * dx + dy * dy);