C++:围绕某个点旋转向量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/620745/
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
C++: Rotating a vector around a certain point
提问by Erik Ahlswede
I am trying to rotate a vector around a certain point on the vector(in C++):
我正在尝试围绕向量上的某个点旋转向量(在 C++ 中):
1 2 3
4 5 6
7 8 9
rotated around the point (1,1) (which is the "5") 90 degrees would result in:
围绕点 (1,1)(即“5”)旋转 90 度将导致:
7 4 1
8 5 2
9 6 3
Right now I am using:
现在我正在使用:
x = (x * cos(90)) - (y * sin(90))
y = (y * cos(90)) + (x * sin(90))
But I don't want it rotated around (0,0)
但我不希望它围绕 (0,0) 旋转
回答by Mark Booth
As Mehrdad Afsharicommented on Pesto's post, including the translation back into the original coordinate system would be:
正如Mehrdad Afshari评论Pesto的帖子,包括翻译回原始坐标系将是:
x_rotated = ((x - x_origin) * cos(angle)) - ((y_origin - y) * sin(angle)) + x_origin
y_rotated = ((y_origin - y) * cos(angle)) - ((x - x_origin) * sin(angle)) + y_origin
回答by Mehrdad Afshari
The solution is to translate the vector to a coordinate system in which the center of rotation is (0,0). Apply the rotation matrix and translate the vector back to the original coordinate system.
解决方案是将向量转换为旋转中心为 (0,0) 的坐标系。应用旋转矩阵并将向量转换回原始坐标系。
dx = x of rotation center
dy = y of rotation center
V2 = V - [dx, dy, 0]
V3 = V2 * rotation matrix
Result = V3 + [dx, dy, 0]
回答by Pesto
Assuming you're using a standard vector implementation where (0,0) would be the top left corner and you're rotating around the point (x_origin, y_origin), this should do it:
假设您使用的是标准向量实现,其中 (0,0) 将是左上角并且您正在围绕点 (x_origin, y_origin) 旋转,这应该这样做:
x = ((x - x_origin) * cos(angle)) - ((y_origin - y) * sin(angle))
y = ((y_origin - y) * cos(angle)) - ((x - x_origin) * sin(angle))
Note that the y's are y_origin - y
because the y value increases as you go down.
请注意,y 是y_origin - y
因为 y 值随着您下降而增加。
回答by Ben S
You will need to use a translation matrixto move rotate about a different point.
您将需要使用平移矩阵来围绕不同的点移动旋转。
回答by SkeletorFromEterenia
I found the answer from Marc Booth to be wrong (rotate (0,1,0) by 0 degrees and you get (0,-1,0) with his formula), and I ended up with:
我发现 Marc Booth 的答案是错误的(将 (0,1,0) 旋转 0 度,你得到 (0,-1,0) 与他的公式),我最终得到:
double cs = cos_deg(new_degrees);
double sn = sin_deg(new_degrees);
double translated_x = x - x_origin;
double translated_y = y - y_origin;
double result_x = translated_x * cs - translated_y * sn;
double result_y = translated_x * sn + translated_y * cs;
result_x += x_origin;
result_y += y_origin;
This can be further simplified of course, but I want to make it as simple as possible.
这当然可以进一步简化,但我想让它尽可能简单。