使正方形旋轉
在此示例中,我們將實際旋轉我們的相機。透過這樣做,它看起來就像我們在旋轉正方形。首先,我們需要一些變數來跟蹤相機的當前旋轉。
注意:將此程式碼新增到您的“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。