我正在写一个涉及立方体的游戏。用户可以从他的角度将单个立方体向左、向右、向上或向下旋转 90 度。
自然,随着形状的旋转,其轴的位置会发生变化,因此下一次旋转可能围绕不同的轴。例如,如果第一次旋转是“右”,我需要绕 Y(垂直)轴正向旋转。现在 Z 轴是 X 轴所在的位置,X 轴是 Z 轴所在的位置,但指向相反的方向。
为此,我使用一个矩阵:
// The matrix used to rotate/tip the shape. This is updated each time we rotate.
private int m_rotationMatrix[][] = { {0, 1, 0}, // User wants to rotate left-right
{1, 0, 0} }; // User wants to rotate up-down
我在每次轮换时更新:
// If we rotated in the x direction, we need to put the z axis where the x axis was
if (0 != leftRight)
{
int newXMatrix[][] = new int[2][3];
for (int direction=0 ; direction<2 ; ++direction)
{
newXMatrix[direction][X_DIMENSION] = m_rotationMatrix[direction][Z_DIMENSION] * (-leftRight);
newXMatrix[direction][Y_DIMENSION] = m_rotationMatrix[direction][Y_DIMENSION]; // Unchanged
newXMatrix[direction][Z_DIMENSION] = m_rotationMatrix[direction][X_DIMENSION] * (leftRight);
}
m_rotationMatrix = newXMatrix;
}
// If we rotated in the y direction, we need to put the z axis where the y axis was
if (0 != upDown)
{
int newXMatrix[][] = new int[2][3];
for (int direction=0 ; direction<2 ; ++direction)
{
newXMatrix[direction][X_DIMENSION] = m_rotationMatrix[direction][X_DIMENSION]; // Unchanged
newXMatrix[direction][Y_DIMENSION] = m_rotationMatrix[direction][Z_DIMENSION] * (upDown);
newXMatrix[direction][Z_DIMENSION] = m_rotationMatrix[direction][Y_DIMENSION] * (-upDown);
}
m_rotationMatrix = newXMatrix;
}
现在,如果我向右、向右、向右转动一个形状,则生成的矩阵与我认为的完全一样:
x y z
Start: LeftRight 0 1 0
UpDown 1 0 0
Right1: LeftRight 0 1 0
UpDown 0 0 1
Right2: LeftRight 0 1 0
UpDown -1 0 0 <-- Looks right to me but doesn't work!
Right3: LeftRight 0 1 0
UpDown 0 0 -1
当我在上述每种情况下测试上下旋转时,三个侧面都是正确的,但在 Right2 情况下是错误的(倒置)。也就是说,如果用户进行“向上”旋转,则 x 旋转将变为 -90 度,我认为这是正确的(x 轴现在指向左侧)但它会导致框从用户的观点,向下。
我发现上下旋转没有这么简单的问题:在任意数量的上下旋转之后,单个左右旋转按预期工作。
作为参考,我的 draw() 这样做:
// Set drawing preferences
gl.glFrontFace(GL10.GL_CW);
// Set this object's rotation and position
gl.glPushMatrix();
gl.glTranslatef(m_xPosition, m_yPosition, m_zPosition - m_selectZ);
gl.glRotatef(m_xRotation, 1, 0, 0);
gl.glRotatef(m_yRotation, 0, 1, 0);
gl.glRotatef(m_zRotation, 0, 0, 1);
...blah blah
我的轮换出了什么问题?