Java:按指定的度数值围绕另一个旋转点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9985473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Rotate Point around another by specified degree value
提问by Aich
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.
我试图用指定的度数值在 Java 中围绕另一个点旋转一个 2D 点,在这种情况下只是围绕 Point (0, 0) 旋转 90 度。
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
预期 (3, 0):X = 0,Y = -3
Returned for (3, 0): X = 1.8369701987210297E-16, Y = 1.8369701987210297E-16
返回 (3, 0):X = 1.8369701987210297E-16,Y = 1.8369701987210297E-16
Expected for (0, -10): X = -10, Y = 0
预期 (0, -10):X = -10,Y = 0
Returned for (0, -10): X = 10.0, Y = 10.0
返回 (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.
方法本身有问题吗?我将该函数从(Rotating A Point In 2D In Lua - GPWiki)移植到 Java。
EDIT:
编辑:
Did some performance tests. I wouldn't have thought so, but the vector solution won, so I'll use this one.
做了一些性能测试。我不会这么想,但矢量解决方案赢了,所以我会使用这个。
回答by Louis Wasserman
If you have access to java.awt
, this is just
如果您有权访问java.awt
,这只是
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];
回答by Peter
You're mutating the X value of center
before performing the calculation on the Y value. Use a temporary point instead.
center
在对 Y 值执行计算之前,您正在改变 X值。改用临时点。
Additionally, that function takes three parameters. Why does yours only take two?
此外,该函数采用三个参数。为什么你的只需要两个?