2015-09-07 71 views
0

我有一个关于atan2()的简单问题,那就是如何从炮塔上获得角度,以便它跟随太空船到哪里去。从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); 
} 

这给我正确的结果,但如何? asan2f给出从斜边到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度的旋转角度通常会指向屏幕顶部的“北”(至少这是它对我的作用方式)。

要从北方= 0转换的角度向东= 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); 
} 
+0

我来自的结果,因为在cocos2d旋转减去90度从北开始,在数学旋转从东方向开始。 – user3191102

+0

我已经添加了另一种方法来管理Cocos2D和“数学”之间的区别。再次,我不记得需要进行翻译。 – PKCLsoft