I've written some code for a player controlling a space ship:
Vector2 currentPositionNormal = this.Position;
currentPositionNormal.Normalize();
Vector2 demandedDirectionNormal = _input.LeftStickPosition;
demandedDirectionNormal.Normalize();
Vector2 velocity = Body.LinearVelocity;
float currentRotationRadians = (float)Math.Atan2(velocity.Y, velocity.X);
float demandedRotationRadians = (float)Math.Atan2(demandedDirectionNormal.Y, demandedDirectionNormal.X);
float rotationDelta = demandedRotationRadians - currentRotationRadians;
Vector2 targetVelocity = Vector2.Zero;
if (rotationDelta < (Info.TurnRate * deltaTime) &&
rotationDelta > -(Info.TurnRate * deltaTime))
{
targetVelocity = new Vector2(
(float)Math.Cos(demandedRotationRadians),
(float)Math.Sin(demandedRotationRadians));
}
else if (rotationDelta > Math.PI)
{
targetVelocity = TurnLeft(currentRotationRadians, deltaTime);
}
else if (rotationDelta < -(float)Math.PI)
{
targetVelocity = TurnRight(currentRotationRadians, deltaTime);
}
else if (rotationDelta > 0)
{
targetVelocity = TurnRight(currentRotationRadians, deltaTime);
}
else if (rotationDelta < 0)
{
targetVelocity = TurnLeft(currentRotationRadians, deltaTime);
}
targetVelocity *= _input.LeftStickPosition.Length();
Body.LinearVelocity = targetVelocity;
Body.Rotation = (float)Math.Atan2(targetVelocity.Y, targetVelocity.X) + (float)(Math.PI / 2); //done because we treat 0 radians as straight up but the engine treats 0 radians as straight right
Body.AngularVelocity = 0;
However, in the case that the player points the control stick straight left, the ship "vibrates". I know it has something to do with the fact that the transition between negative and positive radians happens at the left, but I'm stumped as to what to patch to fix it. Anyone mind helping?