透视投影是用一个四边形的椎体来确定 viewing volume。椎体内的物体可见,椎体外的物体都不会显示。
near 是眼睛到 near clipping plane 的垂直距离
far 是眼睛到 far clipping plane 的垂直距离
fov 是 Y 轴方向上的视角
aspect 是 near clipping plane 的宽高比
可以用 Matrix4.setPerspective(fov, aspect, near, far) 方法计算出投影矩阵
看个例子
6 个三角形
var vertices = new Float32Array([
// Three triangles on the right side
0.75, 1.0, -4.0, 0.4, 1.0, 0.4, // The back green one
0.25, -1.0, -4.0, 0.4, 1.0, 0.4,
1.25, -1.0, -4.0, 1.0, 0.4, 0.4,
0.75, 1.0, -2.0, 1.0, 1.0, 0.4, // The middle yellow one
0.25, -1.0, -2.0, 1.0, 1.0, 0.4,
1.25, -1.0, -2.0, 1.0, 0.4, 0.4,
0.75, 1.0, 0.0, 0.4, 0.4, 1.0, // The front blue one
0.25, -1.0, 0.0, 0.4, 0.4, 1.0,
1.25, -1.0, 0.0, 1.0, 0.4, 0.4,
// Three triangles on the left side
-0.75, 1.0, -4.0, 0.4, 1.0, 0.4, // The back green one
-1.25, -1.0, -4.0, 0.4, 1.0, 0.4,
-0.25, -1.0, -4.0, 1.0, 0.4, 0.4,
-0.75, 1.0, -2.0, 1.0, 1.0, 0.4, // The middle yellow one
-1.25, -1.0, -2.0, 1.0, 1.0, 0.4,
-0.25, -1.0, -2.0, 1.0, 0.4, 0.4,
-0.75, 1.0, 0.0, 0.4, 0.4, 1.0, // The front blue one
-1.25, -1.0, 0.0, 0.4, 0.4, 1.0,
-0.25, -1.0, 0.0, 1.0, 0.4, 0.4
]);
<script id="vertex-shader" type="glsl">
attribute vec4 a_Position;
attribute vec4 a_Color;
uniform mat4 u_ProjMatrix;
uniform mat4 u_ViewMatrix;
varying vec4 v_Color;
void main() {
gl_Position = u_ProjMatrix * u_ViewMatrix * a_Position;
v_Color = a_Color;
}
</script>
<script id="fragment-shader" type="glsl">
precision mediump float;
varying vec4 v_Color;
void main() {
gl_FragColor = v_Color;
}
</script>
view matrix 和 projection matrix
var viewMatrix = new Matrix4();
viewMatrix.setLookAt(0, 0, 5, 0, 0, -100, 0, 1, 0);
var projMatrix = new Matrix4();
projMatrix.setPerspective(30, canvas.width / canvas.height, 1, 100);