dec*_*iar 48 c++ math trigonometry vector rotation
我a坐在坐标处有一个欧几里得矢量(0, 1).我想旋转a通过围绕原点90度(顺时针)(0, 0).
如果我对这应该如何工作有一个正确的理解,旋转后的结果(x,y)坐标应该是(1, 0).如果我将它旋转45度(仍然顺时针),我会期望得到的坐标(0.707, 0.707).
theta = deg2rad(angle);
cs = cos(theta);
sn = sin(theta);
x = x * cs - y * sn;
y = x * sn + y * cs;
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,angle值为90.0度,结果坐标为:(-1, 1).而我真的很困惑.以下链接中的示例代表了上面显示的相同公式?
我做错了什么?或者我误解了矢量是如何旋转的?
Seb*_*olm 78
将矢量旋转90度特别简单.
(x, y)旋转90度左右(0, 0)是(-y, x).
如果你想顺时针旋转,你只需要反过来做,得到(y, -x).
Cas*_*jne 72
你应该从函数中删除变量:
x = x * cs - y * sn; // now x is something different than original vector x
y = x * sn + y * cs;
Run Code Online (Sandbox Code Playgroud)
创建新坐标变为,以避免在到达第二行之前计算x:
px = x * cs - y * sn;
py = x * sn + y * cs;
Run Code Online (Sandbox Code Playgroud)
Alt*_*ivo 19
在0,0附近旋转90度:
x' = -y
y' = x
Run Code Online (Sandbox Code Playgroud)
在px周围旋转90度,py:
x' = -(y - py) + px
y' = (x - px) + py
Run Code Online (Sandbox Code Playgroud)
使用标准类听起来更容易:
std::complex<double> vecA(0,1);
std::complex<double> i(0,1); // 90 degrees
std::complex<double> r45(sqrt(2.0),sqrt(2.0));
vecA *= i;
vecA *= r45;
Run Code Online (Sandbox Code Playgroud)
矢量旋转是复数乘法的子集.
您正在根据新坐标的"新"x部分计算新坐标的y部分.基本上这意味着您根据新输出计算新输出...
尝试根据输入和输出重写:
vector2<double> multiply( vector2<double> input, double cs, double sn ) {
vector2<double> result;
result.x = input.x * cs - input.y * sn;
result.y = input.x * sn + input.y * cs;
return result;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
vector2<double> input(0,1);
vector2<double> transformed = multiply( input, cs, sn );
Run Code Online (Sandbox Code Playgroud)
注意如何为变量选择合适的名称可以完全避免这个问题!