好吧 - 疯了。我正在做一些 WebGL,我正在尝试制作一个等距立方体。我不想使用 Three.js。我想首先了解我的代码出了什么问题。我一直在研究,我能找到的唯一教程似乎是针对 OpenGL 的
无论如何 - 这是我的 drawScene 函数:
function drawScene() {
this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);
mat4.perspective(45, this.gl.viewportWidth / this.gl.viewportHeight, 0.1, 100.0, pMatrix);
mvMatrix = mat4.lookAt([0,0,40], [0, 0, 0], [0, 1, 0]);
_globalNext = this._first;
while(_globalNext) {
_globalNext.render();
}
}
渲染函数是
function render() {
mvPushMatrix();
//transform. order matters.
mat4.translate(mvMatrix, [this._x, this._y, this._z]);
mat4.rotate(mvMatrix, 0.01745*this._rot, [this._axisX, this._axisY, this._axisZ]);
mat4.scale(mvMatrix, [this._scaleX,this._scaleY,this._scaleZ]);
//bind the buffers.
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this._positionBuff);
this.gl.vertexAttribPointer(this._shader.vertexPositionAttribute, this._positionBuff.itemSize, this.gl.FLOAT, false, 0, 0);
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this._colorBuff);
this.gl.vertexAttribPointer(this._shader.vertexColorAttribute, this._colorBuff.itemSize, this.gl.FLOAT, false, 0, 0);
this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, this._indexBuff);
this.setMatrixUniforms(this.gl);
this.gl.drawElements(this.gl.TRIANGLES, this._indexBuff.numItems, this.gl.UNSIGNED_SHORT, 0);
if(this._usePopper == false) {
mvPopMatrix();
}
_globalNext = this._nextSib;
}
相当行人。我用它来画立方体。无论如何,在 OpenGL 示例中他们似乎取消了透视功能,但在这里如果我不这样做,我的场景就是空白。我知道 lookAt 函数工作正常,我必须对透视矩阵做一些事情。一点帮助将不胜感激。谢谢!
最佳答案
投影矩阵所做的只是将场景的坐标系映射到 X 轴和 Y 轴上的 [-1, 1] 范围,这是将片段渲染到窗口时使用的空间。可以以直接渲染到 [-1, 1] 空间的方式构建场景,在这种情况下不需要投影矩阵(这可能是您在示例中所指的,但是通常情况并非如此。
当使用透视矩阵作为投影矩阵时,X 和 Y 坐标会按 Z 值进行缩放,从而使它们看起来有深度。如果该效果不理想,您可以使用正交矩阵消除深度缩放,如下所示:
mat4.ortho(left, right, bottom, top, 0.1, 100.0, pMatrix);
什么是左/右/上/下由您决定,但通常这些将以某种方式与您的 WebGL 视口(viewport)的尺寸相对应。例如,如果您的 WebGL 窗口是 640x480,您可以:
mat4.ortho(0, 640, 0, 480, 0.1, 100.0, pMatrix);
这会导致位于 (0, 0) 的任何顶点在窗口的左下角呈现,而位于 (648, 480) 的任何顶点在右上角呈现。这些顶点的 z 分量将不起作用。这是一种流行的技术,可用于渲染 GUI 元素、 Sprite 或等距图形,就像您尝试做的那样。
希望对您有所帮助!
关于WebGL 等距投影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11088678/