使用 glMatrix 在 WebGL 中环绕立方体

Orbiting a cube in WebGL with glMatrix

https://jsfiddle.net/sepoto/Ln7qvv7w/2/

我设置了一个底座来显示一个具有不同颜色面的立方体。我想要做的是设置一个相机并应用组合的 X 轴和 Y 轴旋转,以便立方体同时绕两个轴旋转。我设置的矩阵似乎有一些问题,因为我可以看到蓝色的脸看起来不太正确。有一些示例说明如何使用旧版本的 glMatrix 完成此操作,但是示例中的代码不再有效,因为 glMatrix 库的 vec4 发生了一些变化。有谁知道如何使用最新版本的 glMatrix 完成此操作,因为我已将 CDN 附加到 fiddle?

谢谢!

            function drawScene() {

            gl.viewport(0,0,gl.viewportWidth, gl.viewportHeight);

            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

            mat4.ortho( mOrtho, -5, 5, 5, -5, 2, -200);

            mat4.identity(mMove);

            var rotMatrix = mat4.create();

            mat4.identity(rotMatrix);

            rotMatrix = mat4.fromYRotation(rotMatrix, yRot,rotMatrix);

            rotMatrix = mat4.fromXRotation(rotMatrix, xRot,rotMatrix);

            mat4.multiply(mMove, rotMatrix, mMove);

            setMatrixUniforms();

            gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);

            gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, triangleVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);

            gl.bindBuffer(gl.ARRAY_BUFFER, triangleColorBuffer);

            gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, triangleColorBuffer.itemSize, gl.FLOAT, false, 0, 0);

            gl.drawArrays(gl.TRIANGLES, 0, triangleVertexPositionBuffer.numItems);

            yRot += 0.01;

            xRot += 0.01;

        }

顾名思义,fromYRotation() 将矩阵初始化为给定的旋转。因此,您需要两个用于部分旋转的临时矩阵,然后您可以将它们合并:

var rotMatrix = mat4.create();
var rotMatrixX = mat4.create();
var rotMatrixY = mat4.create();

mat4.fromYRotation(rotMatrixY, yRot);   
mat4.fromXRotation(rotMatrixX, xRot);
mat4.multiply(rotMatrix, rotMatrixY, rotMatrixX);

你的蓝脸之所以表现异常,是因为缺少深度测试。在您的初始化方法中启用它:

gl.enable(gl.DEPTH_TEST);

您不需要使用三个矩阵:

// you should do allocations outside of the renderloop
var rotMat = mat4.create();

// no need to set the matrix to identity as
// fromYRotation resets rotMats contents anyway
mat4.fromYRotation(rotMat, yRot);
mat4.rotateX(rotMat,xRot);