19 September 2017

Math - rotate a 2D point

I needed a way to rotate a point (x; y) by a certain angle. This turned out to be an easy task:
Vector2 Rotate(Vector2 point, double angle)
{
  double rad = angle * (Math.PI / 180); //First, convert from degrees to radians.
  
  double sin = Math.Sin(rad); //Then, get the sine and
  double cos = Math.Cos(rad); //cosine of this angle.
  
  return new Vector2 //Finally, calculate the rotated point.
  {
    X = point.X * cos - point.Y * sin,
    Y = point.X * sin + point.Y * cos
  };
}