计算出的角度卡在+/- pi / 2范围内

时间:2013-06-18 20:38:12

标签: objective-c kobold2d angle radians

我正在尝试为我正在制作的iPhone游戏制作虚拟操纵杆控制,为此我得到了玩家触摸和操纵杆中心之间的角度,但是当我得到角度时,它只是上升到1.57弧度,然后变为负值,只下降到-1.57,然后再增加到1.57。一旦角度从正切换为负,这会导致我的操纵杆跳到另一侧。

这是我计算角度的方法:

-(double) angleOnCircle: (CGPoint) point1: (CGPoint) centerOfCircle
{
    int point1X = point1.x;
    int point1Y = point1.y;
    int centerX = centerOfCircle.x;
    int centerY = centerOfCircle.y;
    double triangleHeight = point1Y - centerY;
    double triangleBase = point1X - centerX;
    double angle = atan(triangleHeight/triangleBase);
    return angle;
}

这是我更新摇杆位置的地方:

     moveStickAngle = [self angleOnCircle: touchPos : moveStickStartPoint];
    if([self distanceBetweenTwoPoints:touchPos :moveStickStartPoint] < MOVE_STICK_RESTRICTION_RADIUS)
    {
        moveStickCenter = touchPos;
    }
    else
    {
        double newX = MOVE_STICK_START_X + (cos(moveStickAngle) * MOVE_STICK_RESTRICTION_RADIUS);
        double newY = MOVE_STICK_START_Y + (sin(moveStickAngle) * MOVE_STICK_RESTRICTION_RADIUS);
        moveStickCenter = ccp(newX, newY);
    }

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

使用atan2():

double angle = atan2(triangleHeight, triangleBase);

atan2(y,x)正是出于此目的,并返回介于-pi和pi之间的值。

请注意,atan(y / x)无法工作,因为它为(x,y)和(-x,-y)返回相同的值。