0

我正在写一个涉及立方体的游戏。用户可以从他的角度将单个立方体向左、向右、向上或向下旋转 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

我的轮换出了什么问题?

4

1 回答 1

0

我找到了一种方法来完成这项工作。感觉有点笨拙,我还是不明白为什么原来的方法不起作用。如果有人有更好的解决方案,我仍然全神贯注!

我是这样做的:

  • 以自然方向显示形状。
  • 每次用户旋转它时,将该旋转(使用场景轴)添加到旋转列表中。(针对一个方向的多个运动进行优化。)
  • 绘图时,以相反的顺序依次应用每个旋转。

因此,例如,如果用户向右、向上、向右、向右、向下旋转形状,我们将存储一个列表:

  • 右 = 绕 Y 轴旋转 90 度
  • 上 = 绕 X 轴旋转 90 度
  • 右,右 = 绕 Y 轴旋转 180 度
  • 向下 = 绕 X 轴旋转 -90 度

在绘图时,glRotatef 这些以相反的顺序。

这似乎效率低下,我觉得应该有更好的方法。我确定有。但是它工作正常。

于 2015-02-07T10:02:18.170 回答