0
\$\begingroup\$

I am trying to make a function to rotate a point around another point. My maths are very rusty but i did some research and i just dont understand why my function is not working.

public void rotatePoint(int pX,int pY,int angle) {
    int newX = 0, newY = 0; 
    int centerX = 400, centerY = 300;

    angle *= Math.PI / 180; // convert angle from deg to rad

    double rotatedX = Math.cos(angle)*(pX-centerX)-Math.sin(angle)*(pY-centerY) + centerX;
    double rotatedY = Math.sin(angle) * (pX-centerX) + Math.cos(angle) * (pY-centerY) + centerY;

    newX = (int)Math.round(rotatedX);
    newY = (int)Math.round(rotatedY);
}

On the image i just provide my original point is in grey. After a rotation of 90 or 180deg i would expect the point to arrive where the green ones are. They arrive where the red points are.

enter image description here

\$\endgroup\$
0
0
\$\begingroup\$

It looks like your red points are rotated something like 60 degrees from your starting point, rather than the full 90 you expected. Let's investigate why that could be...

angle *= Math.PI / 180;

As we substitute in an initial value of 90 for angle, this translates to...

angle = angle * 3.141592653589 / 180.0
angle = 90 * 0.01745329251
angle = 1.57079632679

But wait, our angle variable is an integer, so we have to truncate to convert this floating point intermediate to an integer value we can store in this variable:

angle = 1 radian

Or about 57 degrees, which matches up to what we're seeing in your graph.

So, use a float or double as your intermediate:

double radianAngle = angle * Math.PI / 180.0;

And compute your sine and cosine ratios off of this fractional intermediate instead.

\$\endgroup\$
2
  • \$\begingroup\$ Tks!! i will try that tomorrow and give feedback but it makes a lot of sense. \$\endgroup\$ Jan 3 '20 at 4:39
  • \$\begingroup\$ Its working, big tks again! \$\endgroup\$ Jan 3 '20 at 20:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .