Java: Rotate Point around another by specified degree value

守給你的承諾、 提交于 2019-12-04 04:14:33

问题


I am trying to rotate a 2D Point in java around another with a specified degree value, in this case simply around Point (0, 0) at 90 degrees.

Method:

public void rotateAround(Point center, double angle) {
    x = center.x + (Math.cos(Math.toRadians(angle)) * (x - center.x) - Math.sin(Math.toRadians(angle)) * (y - center.y));
    y = center.y + (Math.sin(Math.toRadians(angle)) * (x - center.x) + Math.cos(Math.toRadians(angle)) * (y - center.y));
}

Expected for (3, 0): X = 0, Y = -3

Returned for (3, 0): X = 1.8369701987210297E-16, Y = 1.8369701987210297E-16

Expected for (0, -10): X = -10, Y = 0

Returned for (0, -10): X = 10.0, Y = 10.0

Is something wrong with the method itself? I ported the function from (Rotating A Point In 2D In Lua - GPWiki) to Java.

EDIT:

Did some performance tests. I wouldn't have thought so, but the vector solution won, so I'll use this one.


回答1:


If you have access to java.awt, this is just

double[] pt = {x, y};
AffineTransform.getRotateInstance(Math.toRadians(angle), center.x, center.y)
  .transform(pt, 0, pt, 0, 1); // specifying to use this double[] to hold coords
double newX = pt[0];
double newY = pt[1];



回答2:


You're mutating the X value of center before performing the calculation on the Y value. Use a temporary point instead.

Additionally, that function takes three parameters. Why does yours only take two?



来源:https://stackoverflow.com/questions/9985473/java-rotate-point-around-another-by-specified-degree-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!