JS.*_*JS. 4 c++ math graphics rotation
我将一个形状表示为3D中的一组坐标,我试图围绕一个轴旋转整个对象(在这种情况下是Z轴,但是一旦我开始工作,我想绕所有三个旋转) .
我用旋转矩阵写了一些代码来做到这一点:
//Coord is a 3D vector of floats
//pos is a coordinate
//angles is a 3d vector, each component is the angle of rotation around the component axis
//in radians
Coord<float> Polymers::rotateByMatrix(Coord<float> pos, const Coord<float> &angles)
{
float xrot = angles[0];
float yrot = angles[1];
float zrot = angles[2];
//z axis rotation
pos[0] = (cosf(zrot) * pos[0] - (sinf(zrot) * pos[1]));
pos[1] = (sinf(zrot) * pos[0] + cosf(zrot) * pos[1]);
return pos;
}
Run Code Online (Sandbox Code Playgroud)
下图显示了在尝试旋转之前我试图旋转的对象(向下看Z轴),每个小球体表示我正在尝试旋转的坐标之一
alt text http://www.cs.nott.ac.uk/~jqs/notsquashed.png
通过以下代码为对象执行旋转:
//loop over each coordinate in the object
for (int k=start; k<finish; ++k)
{
Coord<float> pos = mp[k-start];
//move object away from origin to test rotation around origin
pos += Coord<float>(5.0,5.0,5.0);
pos = rotateByMatrix(pos, rots);
//wrap particle position
//these bits of code just wrap the coordinates around if the are
//outside of the volume, and write the results to the positions
//array and so shouldn't affect the rotation.
for (int l=0; l<3; ++l)
{
//wrap to ensure torroidal space
if (pos[l] < origin[l]) pos[l] += dims[l];
if (pos[l] >= (origin[l] + dims[l])) pos[l] -= dims[l];
parts->m_hPos[k * 4 + l] = pos[l];
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,当我以这种方式执行旋转时,如果将角度参数设置为(0.0,0.0,1.0),则它可以工作(排序),但是对象会变形,如下所示:
alt text http://www.cs.nott.ac.uk/~jqs/squashed.png
这不是我想要的.任何人都可以告诉我我做错了什么以及如何围绕轴旋转整个物体而不会变形?
谢谢
nodlams
在rotateByMatrix中进行旋转的地方,你计算新的pos [0],然后将其输入下一行以计算新的pos [1].所以你用来计算新pos [1]的pos [0]不是输入,而是输出.将结果存储在temp var中并返回该值.
Coord<float> tmp;
tmp[0] = (cosf(zrot) * pos[0] - (sinf(zrot) * pos[1]));
tmp[1] = (sinf(zrot) * pos[0] + cosf(zrot) * pos[1]);
return tmp;
Run Code Online (Sandbox Code Playgroud)
另外,将pos作为const引用传递给函数.
const Coord<float> &pos
Run Code Online (Sandbox Code Playgroud)
此外,您应该计算一次sin和cos值,将它们存储在临时值中并重复使用它们.
| 归档时间: |
|
| 查看次数: |
3762 次 |
| 最近记录: |