This may have been asked already, but I was unable to find it, because I don't really know what I'm looking for. I drew a picture:
I need theta. I've seen various solutions using Vector.Dot
, and Math.Atan2
, but they don't seem to work...
BTW, I need the output in degrees. On previous tries, I ran my results through MathHelper.ToDegrees()
, but got values over 360, which shouldn't be possible.
This is my current code:
Vector2 mouse = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);
Vector2 delta = mouse - Position;
angle = Math.Atan2(delta.X, -delta.Y);
angle = MathHelper.ToDegrees((float)angle);
EDIT: A little more info. I'm making a 2D game, and need the angle to 'rotate' one of my sprites (simply changing which sprite I'm displaying). The code for how I'm doing this is below.
public static Direction GetDirection(double radians)
{
if (radians > GetRadians(Direction.Up).Lower && radians < GetRadians(Direction.Up).Upper)
{
return Direction.Up;
}
else if (radians > GetRadians(Direction.UpRight).Lower && radians < GetRadians(Direction.UpRight).Upper)
{
return Direction.UpRight;
}
else if (radians > GetRadians(Direction.Right).Lower && radians < GetRadians(Direction.Right).Upper)
{
return Direction.Right;
}
else if (radians > GetRadians(Direction.DownRight).Lower && radians < GetRadians(Direction.DownRight).Upper)
{
return Direction.DownRight;
}
else if (radians > GetRadians(Direction.Down).Lower && radians < GetRadians(Direction.Down).Upper)
{
return Direction.Down;
}
else if (radians > GetRadians(Direction.DownLeft).Lower && radians < GetRadians(Direction.DownLeft).Upper)
{
return Direction.DownLeft;
}
else if (radians > GetRadians(Direction.Left).Lower && radians < GetRadians(Direction.Left).Upper)
{
return Direction.Left;
}
else
{
return Direction.UpLeft;
}
}
public static Radians GetRadians(Direction direction)
{
Radians r = new Radians(0,0);
switch (direction)
{
case Direction.Up:
r = new Radians(15 * increment, increment);
break;
case Direction.UpRight:
r = new Radians(1 * increment, 3 * increment);
break;
case Direction.Right:
r = new Radians(3 * increment, 5 * increment);
break;
case Direction.DownRight:
r = new Radians(5 * increment, 7 * increment);
break;
case Direction.Down:
r = new Radians(7 * increment, 9 * increment);
break;
case Direction.DownLeft:
r = new Radians(9 * increment, 11 * increment);
break;
case Direction.Left:
r = new Radians(11 * increment, 13 * increment);
break;
case Direction.UpLeft:
r = new Radians(13 * increment, 15 * increment);
break;
}
return r;
}
atan2
implementations have X and Y reversed, so the first parameter isy
, followed byx
. Check a reference to see if that's the case. \$\endgroup\$