So, my goal is to rotate one point around another point, which shouldn't be hard. I found some code answers and the math itself also has countles examples.
But my positions after the rotation process are just straight up wrong.
My currently not working solution is like this solution, I already tried both answers tho (and countless more)
static Point RotatePoint(Point pointToRotate, Point centerPoint, double angleInDegrees)
{
double angleInRadians = angleInDegrees * (Math.PI / 180);
double cosTheta = Math.Cos(angleInRadians);
double sinTheta = Math.Sin(angleInRadians);
// Change point to rotate, so the center / pivot point is treated as the origin (0|0)
pointToRotate.X -= centerPoint.X;
pointToRotate.Y -= centerPoint.Y;
// Rotate the point by the degrees
pointToRotate.X = pointToRotate.X * cosTheta - pointToRotate.Y * sinTheta;
pointToRotate.Y = pointToRotate.X * sinTheta pointToRotate.Y * cosTheta;
// Change the point back to the position it actually has
pointToRotate.X = centerPoint.X;
pointToRotate.Y = centerPoint.Y;
return pointToRotate;
}
One answer suggested to change the calculation to
pointToRotate.X = pointToRotate.X * cosTheta pointToRotate.Y * sinTheta;
pointToRotate.Y = -1 * (pointToRotate.X * sinTheta) pointToRotate.Y * cosTheta;
without any additional reasoning tho. Doesn't solve it for me anyway.
The data I test with is
Degrees: 90
center point: {0,0}
point 1: {6.13,0}
point 2: {0.13,4.25}
result point 1: {3.75341847446559E-16,3.75341847446559E-16}
result point 2: {-4.25,-4.25}
What is going wrong, these points are not even close? point one should be {0,6.13} after it has been rotated 90°. I used the COS and SIN method like microsoft described
CodePudding user response:
The problem is you're changing pointToRotate.X
in pointToRotate.X = pointToRotate.X * cosTheta - pointToRotate.Y * sinTheta;
and then using the changed value in pointToRotate.Y = pointToRotate.X * sinTheta pointToRotate.Y * cosTheta;
.
You need to use the ORIGINAL value of X
in the second calculation.
Change your code to this:
static Point RotatePoint(Point pointToRotate, Point centerPoint, double angleInDegrees)
{
double angleInRadians = angleInDegrees * (Math.PI / 180);
double cosTheta = Math.Cos(angleInRadians);
double sinTheta = Math.Sin(angleInRadians);
// Change point to rotate, so the center / pivot point is treated as the origin (0|0)
pointToRotate.X -= centerPoint.X;
pointToRotate.Y -= centerPoint.Y;
// Rotate the point by the degrees
double x = pointToRotate.X * cosTheta - pointToRotate.Y * sinTheta;
double y = pointToRotate.X * sinTheta pointToRotate.Y * cosTheta;
// Change the point back to the position it actually has
x = centerPoint.X;
y = centerPoint.Y;
return new Point(x, y);
}
I recommend learning how to single-step your code in a debugger. If you did that you'd have realised the mistake as soon as you inspected the values in the calculation for Y
...