我测试三种方案
- 老师的
gl-matrix
的mat4
的perspective
- chatgpt 生成的
import {mat4} from 'gl-matrix'
const WIDTH = 500
const HEIGHT = 500
/**
* getPerspectiveMatrix 获取透视投影矩阵 (chatgpt 给出的)
* @param {number} fieldOfView 视野角度,单位为弧度
* @param {number} aspectRatio 宽高比
* @param {number} nearPlane 近平面距离
* @param {number} farPlane 远平面距离
* @returns {Float32Array<number>} 透视投影矩阵,使用 Float32Array 表示
*/
const getPerspectiveMatrix = (fieldOfView, aspectRatio, nearPlane, farPlane) => {
const f = Math.tan(Math.PI * 0.5 - 0.5 * fieldOfView);
const rangeInv = 1.0 / (nearPlane - farPlane);
return new Float32Array([
f / aspectRatio, 0, 0, 0,
0, f, 0, 0,
0, 0, (nearPlane + farPlane) * rangeInv, -1,
0, 0, nearPlane * farPlane * rangeInv * 2, 0
]);
}
// 获取透视投影矩阵 (老师的)
function getPerspective(fov, aspect, far, near) {
fov = fov * Math.PI / 180;
return new Float32Array([
1/(aspect*Math.tan(fov / 2)), 0, 0, 0,
0, 1/(Math.tan(fov/2)),0,0,
0,0,-(far+near)/(far-near),-(2*far*near)/(far-near),
0,0,-1,0,
])
}
const perspectiveMatrix1 = getPerspective(150, WIDTH / HEIGHT, 100, 1) // 老师的
const perspectiveMatrix2 = mat4.perspective(new Float32Array(16), 150, WIDTH / HEIGHT, 1, 100) // gl-matrix
const perspectiveMatrix3 = getPerspectiveMatrix(150, WIDTH / HEIGHT, 1, 100) // chatgpt
console.log(perspectiveMatrix1) // 老师的
console.log(perspectiveMatrix2) // gl-matrix
console.log(perspectiveMatrix3) // chatgpt
返回结果: