2015-09-07 60 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