Ali
Ali

Reputation: 265

Find the direction of rotation of a sprite i.e. clockwise or anticlockwise

I've been beating myself at this because I think its an easy problem but somehow I just can't find a solution to it.

I'm rotating a CCSprite about its anchor point depending on touch move events. Here is the code I use to rotate the sprite.

CGPoint previousLocation = [touch previousLocationInView:[touch view]];
CGPoint newLocation = [touch locationInView:[touch view]];

//preform all the same basic rig on both the current touch and previous touch
CGPoint previousGlLocation = [[CCDirector sharedDirector] convertToGL:previousLocation];
CGPoint newGlLocation = [[CCDirector sharedDirector] convertToGL:newLocation];

CCSprite *handle = (CCSprite*)[_spriteManager getChildByTag:HANDLE_TAG];

CGPoint previousVector = ccpSub(previousGlLocation, handle.position);
CGFloat firstRotateAngle = -ccpToAngle(previousVector);
CGFloat previousTouch = CC_RADIANS_TO_DEGREES(firstRotateAngle);

CGPoint currentVector = ccpSub(newGlLocation, handle.position);
CGFloat rotateAngle = -ccpToAngle(currentVector);
CGFloat currentTouch = CC_RADIANS_TO_DEGREES(rotateAngle);

float rotateAmount = (currentTouch - previousTouch);
handle.rotation += rotateAmount;

I need to somehow find what is the direction of rotation i.e. is the direction clockwise or anticlockwise. I tried doing this by setting up an 'if' condition on the rotateAmount value. But this does not work in one specific case.

For eg. If the user is rotating the sprite in the clockwise direction, in this case the rotateAmount value will be positive from 0 - 359. The moment the user is about to complete the circle the condition would not hold true and the direction would change to anticlockwise.

Is there a better way of detecting the direction of rotation?

Upvotes: 3

Views: 959

Answers (1)

bshirley
bshirley

Reputation: 8356

try this wrap-around sanity check:

float rotateAmount = (currentTouch - previousTouch);

if (rotateAmount > 180)
  rotateAmount -= 360;
else if (rotateAmount < -180)
  rotateAmount += 360;

handle.rotation += rotateAmount;

Upvotes: 5

Related Questions