2009-11-07 71 views
4

我将一个形状表示为一组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; 
} 

下图显示了我想要旋转(向下看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]; 
    } 
} 

的问题是,当我以这种方式进行旋转,与角度参数设置为(0.0,0.0,1.0)它的工作原理(在某种程度上),但对象发生变形,像这样:

alt text http://www.cs.nott.ac.uk/~jqs/squashed.png

这不是我想要的。任何人都可以告诉我我做错了什么,以及如何绕轴旋转整个对象而不会使其变形?

感谢

nodlams

+1

你的轮换代码看起来不错。尝试它没有你的包装代码? – rlbond

+0

我刚试过,没有换行代码,很不幸,它没有改变。 –

+1

我不确定...但在旋转函数的第二个语句中(即pos [1] = ...),您正在使用pos [0]的更新值。这是打算吗? – Ponting

回答

7

哪里你做你的旋转rotateByMatrix,你计算出新的POS [0],但随后即饲料到下一行用于计算新的POS [1]。所以你用来计算新pos [1]的pos [0]不是输入,而是输出。将结果存储在临时变量中并返回。

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; 

另外,将pos作为const引用传入函数。

const Coord<float> &pos 

另外,您应该计算罪,一旦将CoS值,将其存储在临时变量并重新使用它们。

+0

啊,那是行得通的,我是新来的,我一定在某个地方犯了一个愚蠢的错误。谢谢你的帮助! –