旋转精灵面对一个点(cocos2d)

时间:2012-05-16 08:40:09

标签: iphone ios ipad cocos2d-iphone

我似乎在计算我的精灵和触摸点之间的角度时遇到了问题。我试图让我的精灵在用户触摸屏幕时直接面对触摸点的方向。这是我的代码:

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    CGPoint tapPosition;
    for (UITouch *touch in touches){
        CGPoint location = [touch locationInView:[touch view]];
        tapPosition = [self convertToNodeSpace:[[CCDirector sharedDirector] convertToGL:location]];
    }

    float angle = CC_RADIANS_TO_DEGREES(ccpAngle(fish.position, tapPosition));
    [fish runAction:[CCRotateTo actionWithDuration:0.5 angle:angle]];
}

有什么想法吗?感谢

3 个答案:

答案 0 :(得分:4)

将此添加到Nikhil的答案结尾,以避免在触摸位置位于精灵的右下角时产生负角度。

if (calculatedAngle < 0) 
{
     calculatedAngle+=360;
}

答案 1 :(得分:3)

尝试这一点,首先你不需要那个for循环,因为你最终会以最后一个触摸位置结束。您也可以使用[touch anyObject],如下所示。

其次,我不确定ccpAngle在我的头脑中做了什么,但是当这样的宏不起作用时,自己更容易自己做数学。

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   CGPoint tapPosition;
   UITouch *touch = [touches anyObject];

   CGPoint location = [touch locationInView:[touch view]];
   tapPosition = [self convertToNodeSpace:[[CCDirector sharedDirector] convertToGL:location]];

   float dY = fish.position.y - tapPosition.y;
   float dX = fish.position.x - tapPosition.x;
   float offset = dX<0 ? 90.0f : -90.0f;
   float angle = CC_RADIANS_TO_DEGREES(atan2f(dY, dX)) + offset;

   [fish runAction:[CCRotateTo actionWithDuration:0.5 angle:angle]];
}

你可能也可以用来自ccpDiff的点代替dX和dY,但这并不重要。另外,根据鱼头的位置,你可能需要调整角度偏移,但我会把它留给你。

如果有帮助,请告诉我。

答案 2 :(得分:3)

CCPoint pos1 = [鱼位]; CCPoint pos2 = touchlocation;

float theta = atan((pos1.y-pos2.y)/(pos1.x-pos2.x)) * 180 * 7 /22;

float calculatedAngle;

if(pos1.y - pos2.y > 0)
{
    if(pos1.x - pos2.x < 0)
    {
        calculatedAngle = (-90-theta);
    }
    else if(pos1.x - pos2.x > 0)
    {
       calculatedAngle = (90-theta);
    }       
}
else if(pos1.y - pos2.y < 0)
{
    if(pos1.x - pos2.x < 0)
    {
       calculatedAngle = (270-theta);
    }
    else if(pos1.x - pos2.x > 0)
    {
       calculatedAngle = (90-theta);
    }
}

在你的行动中使用这个calculatedAngle ..希望这有助于......:)