Search code examples
ioscocos2d-iphonerotationjoystick

Rotating a Cocos2d sprite to match a joystick


I'm using a SneakyJoystick in Cocos2d, and I'm trying to get a sprite to rotate to face the same direction as the joystick is pointed (this is top down).

I can get it to rotate to face it, but it snaps into position as the rotation is updated every frame or so.

How can I make the sprite rotate smoothly towards the target angle, without jumping to it? I wasn't able to figure out how to do this with a CCRotateTo because the angle to rotate towards could change at any time.


Solution

  • I ended up fixing this simply by using a rotation method that I made, which rotates the node/sprite in the correct direction at the correct amount each update.

    - (void)rotateNode:(CCNode*)aNode degrees:(float)targetRotation withSpeed:(float)rotationSpeed withTimeDelta:(ccTime)dt
    {
        rotationSpeed = rotationSpeed * dt;
    
        // Convert the difference between the two angles to radians
        float diff = (targetRotation - aNode.rotation) * (M_PI / 180);
        // Find the rotation of the vector created by the sin and cos of the difference
        float rotationDifference = atan2f(sinf(diff),cosf(diff));
        // Rotate the clip accordingly
        aNode.rotation += MAX(
                             MIN(
                                 (180/M_PI) * rotationDifference,rotationSpeed), -rotationSpeed
                             );
    }