關於three.js中的矩陣更新

1. 概述

使用如下代碼繪製一個面:

'use strict';

function init() {
    //console.log("Using Three.js version: " + THREE.REVISION);   

    // create a scene, that will hold all our elements such as objects, cameras and lights.
    var scene = new THREE.Scene();

    // create a camera, which defines where we're looking at.
    var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);

    // position and point the camera to the center of the scene
    camera.position.set(0, 0, 100);   //相機的位置
    camera.up.set(0, 1, 0);         //相機以哪個方向爲上方
    camera.lookAt(new THREE.Vector3(1, 2, 3));          //相機看向哪個座標。

    console.log(camera.matrixWorldInverse);
 
    // create a render and set the size
    var renderer = new THREE.WebGLRenderer();
    renderer.setClearColor(new THREE.Color(0x000000));
    renderer.setSize(window.innerWidth, window.innerHeight);

    // add the output of the renderer to the html element
    document.getElementById("webgl-output").appendChild(renderer.domElement);

    
    // create the ground plane
    var planeGeometry = new THREE.PlaneGeometry(60, 20);
    var planeMaterial = new THREE.MeshBasicMaterial({
        color: 0xAAAAAA
    });

    var plane = new THREE.Mesh(planeGeometry, planeMaterial);

    // add the plane to the scene
    scene.add(plane);

    // rotate and position the plane    
    plane.position.set(15, 8, -10);
    plane.rotation.x = THREE.Math.degToRad(30);
    plane.rotation.y = THREE.Math.degToRad(45);
    plane.rotation.z = THREE.Math.degToRad(60);

    console.log(plane.matrixWorld);
 
    renderer.render(scene, camera);
}

打印輸出的視圖矩陣和模型矩陣如下:
imglink1

而去掉最後的渲染語句:

renderer.render(scene, camera);

之後,打印輸出的視圖矩陣和模型矩陣如下:
imglink2

可以發現兩者的輸出結果並不一致,這其實涉及到three.js中矩陣更新的問題。

2. 詳解

three.js中的Mesh和Camera都繼承自Object3D,Object3D提供了更新圖形矩陣的接口:
imglink3

在分別設置Mesh和camera的圖形變換參數之後,需要調用updateMatrixWorld()才能保證圖形矩陣正確:

camera.updateMatrixWorld(true);
plane.updateMatrixWorld(true);

但是在調用renderer.render之後,three.js就會使得矩陣自動進行更新。所以除非必要,模型矩陣和視圖矩陣可以不用顯示更新。而console.log是異步操作,所以會出現打印信息是正常的現象。如果是單步調式模式,如果不調用updateMatrixWorld(),顯示的就會是初始化的矩陣信息。

除此之外,Camera的投影矩陣也值得注意。PerspectiveCamera提供了更新投影矩陣的接口:
imglink4
文檔很明確的說明了,在改變Camera的投影參數之後,必須調用一次updateProjectionMatrix才能使Camera的效果生效。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章