找到精灵的旋转方向,即顺时针或逆时针

时间:2013-04-08 17:38:50

标签: iphone ios vector cocos2d-iphone

我一直在为此而努力,因为我认为这是一个简单的问题但不知何故我找不到解决方案。

我正在根据触摸移动事件旋转关于其锚点的CCSprite。这是我用来旋转精灵的代码。

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;

我需要以某种方式找到旋转方向,即顺时针方向或逆时针方向。我尝试通过在rotateAmount值上设置'if'条件来做到这一点。但这在一个特定情况下不起作用。

例如。如果用户以顺时针方向旋转精灵,在这种情况下,rotateAmount值将从0到359为正。当用户即将完成圆圈时,条件将不成立,方向将变为逆时针方向。

有没有更好的方法来检测旋转方向?

1 个答案:

答案 0 :(得分:5)

尝试这种环绕式健全性检查:

float rotateAmount = (currentTouch - previousTouch);

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

handle.rotation += rotateAmount;