2013-06-20 207 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°顺时针或逆时针。