Rotate a point around another point code

If you need to rotate a point around another point in 2D then here is a nice function. The below is in C#.

/// <summary>
/// Rotates 'p1' about 'p2' by 'angle' degrees clockwise.
/// </summary>
/// <param name="p1">Point to be rotated</param>
/// <param name="p2">Point to rotate around</param>
/// <param name="angle">Angle in degrees to rotate clockwise</param>
/// <returns>The rotated point</returns>
public Point RotatePoint(Point p1, Point p2, double angle) {

    double radians = ConvertToRadians(angle);
    double sin = Math.Sin(radians);
    double cos = Math.Cos(radians);

    // Translate point back to origin
    p1.X -= p2.X;
    p1.Y -= p2.Y;

    // Rotate point
    double xnew = p1.X * cos - p1.Y * sin;
    double ynew = p1.X * sin + p1.Y * cos;
    
    // Translate point back
    Point newPoint = new Point((int)xnew + p2.X, (int)ynew + p2.Y);
    return newPoint;
 }

 public double ConvertToRadians(double angle) {
     return (Math.PI / 180) * angle;
 }

Enjoy 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *