Three.js 新舊版本建立幾何物件差異

songofhawk發表於2021-12-16

昨天遇到個小問題,也搞了挺長時間:用Three.js在webgl中繪製三維物件,從網上抄的一段程式碼,執行報錯:

THREE.Geometry is not a constructor

納尼,找不到Geometry物件?

function createLine(){
        let start = new THREE.Vector3(7, 1.8, -2);
        let end = new THREE.Vector3(1.6,1.8, -2);

        // 就是這裡建立的物件找不到 *****
        let geometry = new THREE.Geometry();
        // ****************************

        let lineMaterial = new THREE.LineBasicMaterial({color: 0x00ff00});
        geometry.vertices.push(start);
        geometry.vertices.push(end);
        let line = new THREE.Line(lineGeometry, lineMaterial);
        scene.add(line);
        return line;
}

一開始還以為是模組匯入問題,折騰了一陣才發現,THREE模組中竟然真的就沒有Geometry!難道網上的程式碼是愚人節貼的?遇事不決問google,終於確認人家是升級了。新版的Three.js不再提供Geometry物件,代之以BufferGeometry,程式碼修改如下:

function createLine(){
        let start = new THREE.Vector3(7, 1.8, -2);
        let end = new THREE.Vector3(1.6,1.8, -2);

        let lineMaterial = new THREE.LineBasicMaterial({color: 0x00ff00});
        let pointsArray = [start, end];
        let lineGeometry = new THREE.BufferGeometry().setFromPoints(pointsArray);
        let line = new THREE.Line(lineGeometry, lineMaterial);
        scene.add(line);
        return line;
}

相關文章