使正方形旋转
在此示例中,我们将实际旋转我们的相机。通过这样做,它看起来就像我们在旋转正方形。首先,我们需要一些变量来跟踪相机的当前旋转。
注意:将此代码添加到您的“webgl-demo.js”脚本的开头
js
let squareRotation = 0.0;
let deltaTime = 0;
现在我们需要更新 drawScene() 函数,以便在绘制正方形时将当前旋转应用于相机。将相机平移到正方形的初始绘制位置后,我们应用旋转。
在您的“draw-scene.js”模块中,更新您的 drawScene() 函数声明,以便它可以传递要使用的旋转
js
function drawScene(gl, programInfo, buffers, squareRotation) {
// …
}
在您的 drawScene() 函数中,紧跟在 mat4.translate() 调用之后,添加此代码
js
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
squareRotation, // amount to rotate in radians
[0, 0, 1],
); // axis to rotate around
这会围绕 Z 轴按 squareRotation 的当前值旋转 modelViewMatrix。
要真正实现动画,我们需要添加代码来随着时间改变 squareRotation 的值。
将此代码添加到您的 main() 函数末尾,替换现有的 drawScene() 调用
js
let then = 0;
// Draw the scene repeatedly
function render(now) {
now *= 0.001; // convert to seconds
deltaTime = now - then;
then = now;
drawScene(gl, programInfo, buffers, squareRotation);
squareRotation += deltaTime;
requestAnimationFrame(render);
}
requestAnimationFrame(render);
此代码使用 requestAnimationFrame 来请求浏览器在每一帧上调用 render 函数。requestAnimationFrame 向我们传递自页面加载以来的毫秒数。我们将其转换为秒,然后从中减去上次时间以计算 deltaTime,即自上一帧渲染以来的秒数。
最后,我们更新 squareRotation。