2013-06-20 199 views
0

我正在繪製路徑並沿其移動精靈。現在我想讓這個精靈在每個航點之後總是看着駕駛方向。使用此代碼我可以設置方向(非平滑)。 getTargetAngle返回新的旋轉角度。AndEngine沿路徑平滑旋轉

float angleDeg = getTargetAngle(sprite.getX(), sprite.getY(), targetX[pWaypointIndex + 1], targetY[pWaypointIndex + 1]); 
sprite.setRotation(angleDeg); 

現在我可以在轉折點做成爲平滑,除了即時從-179°到179°,在那裏它沿着長路徑,而不是短匝,使跳轉:

sprite.unregisterEntityModifier(rotMod); 
rotMod = new RotationModifier(0.5f, currentAngleDeg, angleDeg); 
sprite.registerEntityModifier(rotMod); 

當兩個角度的絕對值都超過180°時,我試圖將360°添加到子圖的當前角度。從-179°跳到179°跳到181跳到179,但這不起作用。

if(Math.abs((float)angleDeg) + Math.abs((float)currentAngleDeg) > 180) { 
if (currentAngleDeg < 0) { 
    currentAngleDeg+=360.0f; 
} else { 
    currentAngleDeg-=360.0f; 
} 

getTargetAngle:

public float getTargetAngle(float startX, float startY, float   targetX, float targetY){ 

    float dX = targetX - startX; 
    float dY = targetY - startY; 
    float angleRad = (float) Math.atan2(dY, dX); 
    float angleDeg = (float) Math.toDegrees(angleRad); 
    return angleDeg; 
} 
+0

嗨,你可以顯示getTargetAngle()的代碼嗎?如果我調用.registerEntityModifier(新的RotationModifier(0.5f,181.0f,179.0f)),它會旋轉,因爲我懷疑您需要,逆時針旋轉2°,這與您的情況相同,即,如果以這種方式進行硬編碼? – Steven

+0

添加了有問題的代碼 – user2481233

+0

下面的代碼排序了這個問題嗎? – Steven

回答

1

的問題是,旋轉始終相對於場景的軸取向。函數getTargetAngle()給出的角度需要與精靈當前的旋轉有關。

請嘗試以下方法,

刪除添加/膠層360°的代碼,然後用下面的代碼替換您的getTargetAngle()函數,

public float getTargetAngle(float startX, float startY, float startAngle, float targetX, float targetY){ 

    float dX = targetX - startX; 
    float dY = targetY - startY; 

    //find the coordinates of the waypoint in respect to the centre of the sprite 
    //with the scene virtually rotated so that the sprite is pointing at 0° 

    float cos = (float) Math.cos(Math.toRadians(-startAngle)); 
    float sin = (float) Math.sin(Math.toRadians(-startAngle)); 

    float RotateddX = ((dX * cos) - (dY * sin)); 
    float RotateddY = ((dX * sin) + (dY * cos)); 

    //Now get the angle between the direction the sprite is pointing and the 
    //waypoint 
    float angleRad = (float) Math.atan2(RotateddY, RotateddX); 

    float angleDeg = (float) Math.toDegrees(angleRad); 
    return angleDeg; 
} 

然後當你到達航點,

sprite.unregisterEntityModifier(rotMod); 
float angleDeg = getTargetAngle(sprite.getX(), sprite.getY(), sprite.getRotation(), targetX[pWaypointIndex + 1], targetY[pWaypointIndex + 1]); 
rotMod = new RotationModifier(0.5f, sprite.getRotation(), sprite.getRotation() + angleDeg); 
sprite.registerEntityModifier(rotMod); 

請注意,旋轉修飾符將來自getTargetAngle()的返回值添加到現有的精靈旋轉上 - 現在是相對於現有角度的角度樂。

旋轉將始終發生在角度方向< = 180°順時針或逆時針。