I'm trying to rotate a sprite to face the mouse by incrementing and decrementing the Rotation using a turning radius. It works fine up until the point where the mouse is top-left and moves to the top-right. I have it so that if the angle difference is greater than the current Rotation value, the sprite's Rotation gets incremented, otherwise it gets decremented. So when it goes from 6.5 radians to 0, it rotates counterclockwise by 350-some degrees, instead of clockwise by 15-some degrees. Me and others have been working on this all day and have no idea how to solve this. My code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.IO;
namespace Physics
{
public class Ship
{
public Texture2D Texture { get; set; }
public Vector2 Position { get; set; }
public double Rotation { get; set; }
MouseState prevState, currState;
Vector2 A, B;
public const double NINETY_DEGREES = 1.57079633;
double turningRadius = 2 * (Math.PI / 180);
double targetRotation, rotationDifferential;
public Ship(Texture2D texture, Vector2 position)
{
Texture = texture;
Position = position;
A = new Vector2(Position.X, Position.Y);
B = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);
Rotation = 0;
}
public void Update()
{
currState = Mouse.GetState();
A.X = Position.X;
A.Y = Position.Y;
B.X = currState.X;
B.Y = currState.Y;
if (B.Y > A.Y)
if (B.X > A.X) //Bottom-right
targetRotation = Math.Atan((B.Y - A.Y) / (B.X - A.X)) + NINETY_DEGREES;
else //Bottom-left
targetRotation = (Math.Atan((A.X - B.X) / (B.Y - A.Y))) + (NINETY_DEGREES * 2);
else
if (B.X > A.X) //Top-right
targetRotation = Math.Atan((B.X - A.X) / (A.Y - B.Y));
else //Top-Left
targetRotation = Math.Atan((A.Y - B.Y) / (A.X - B.X)) + (NINETY_DEGREES * 3);
if (Rotation > targetRotation)
Rotation -= turningRadius;
else
Rotation += turningRadius;
prevState = currState;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position, null, Color.White, (float)Rotation, new Vector2(Texture.Width / 2, Texture.Height / 2), 0.5f,
SpriteEffects.None, 0.0f);
}
}
}