从atan2获得角度

时间:2015-09-07 09:25:33

标签: math vector cocos2d-iphone angle

我对atan2()有一个简单的问题,就是如何从炮塔获得角度,以便它跟随太空飞船前进。

我有一个从炮塔到太空船的矢量但据我所知atan2f给出了从斜边到0度线的角度。

如果我错了,请纠正我。

enter image description here

我希望将该角度突出显示为(蓝色),以便它跟随宇宙飞船前进的位置。

这是我的代码:

-(void) upDateTurret:(CCTime)delta{

CGPoint playerToCannonVector = ccpSub(_playerSprite.position, _turretSprite.position);

float angle = atan2f(playerToCannonVector.y, playerToCannonVector.x);

_turretSprite.rotation = 90.0f - CC_RADIANS_TO_DEGREES(angle);
}

这给我正确的结果但是如何? as atan2f给出从斜边到0度线(红色角度)的角度。

1 个答案:

答案 0 :(得分:0)

这就是我使用的:

// Calculates the angle from one point to another, in radians.
//
+ (float) angleFromPoint:(CGPoint)from toPoint:(CGPoint)to {
    CGPoint pnormal = ccpSub(to, from);
    float radians = atan2f(pnormal.x, pnormal.y);

    return radians;
}

它基本上匹配您自己的代码;唯一真正的区别是你从90.0度减去结果,这是我认为你缺少的。请记住,0度的旋转通常会指向“北”到屏幕的顶部(至少这对我来说是这样的)。

要将角度从north = 0转换为east = 0,我使用:

// Converts an angle in the world where 0 is north in a clockwise direction to a world
// where 0 is east in an anticlockwise direction.
//
+ (float) angleFromDegrees:(float)deg {
    return fmodf((450.0f - deg), 360.0);
}