[WebAR和WebVR學(xué)習(xí)之路]組成Three.js場景的基本組件

組成Three.js場景的基本組件

《創(chuàng)建場景》

場景中的基本組件:相機(jī)、光源和幾何體

THREE.Scene()對象就是以上基本組件的一個容器。

習(xí)題2-1:

創(chuàng)建一個平面、相機(jī)和適當(dāng)光源。在dat.GUI中創(chuàng)建Add Cube和Remove Cube按鈕,并顯示目前場景中物體的個數(shù)。Add Cube和Remove Cube會分別在平面的上方創(chuàng)建或移除一個Cube,Cube保持第一章中的自旋動畫并使用UI控制。

<!DOCTYPE html>

<html>

<head>
    <title>Example 02.01 - Basic Scene</title>
    <script type="text/javascript" src="../libs/three.js"></script>

    <script type="text/javascript" src="../libs/stats.js"></script>
    <script type="text/javascript" src="../libs/dat.gui.js"></script>
    <style>
        body {
            /* set margin to 0 and overflow to hidden, to go fullscreen */
            margin: 0;
            overflow: hidden;
        }
    </style>
</head>
<body>

<div id="Stats-output">
</div>
<!-- Div which will hold the Output -->
<div id="WebGL-output">
</div>

<!-- Javascript code that runs our Three.js examples -->
<script type="text/javascript">

    // once everything is loaded, we run our Three.js stuff.
    function init() {

        var stats = initStats();

        // 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);
        scene.add(camera);

        // create a render and set the size
        var renderer = new THREE.WebGLRenderer();

        renderer.setClearColor(new THREE.Color(0xEEEEEE, 1.0));
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.shadowMapEnabled = true;

        // create the ground plane
        var planeGeometry = new THREE.PlaneGeometry(60, 40, 1, 1);
        var planeMaterial = new THREE.MeshLambertMaterial({color: 0xffffff});
        var plane = new THREE.Mesh(planeGeometry, planeMaterial);
        plane.receiveShadow = true;

        // rotate and position the plane
        plane.rotation.x = -0.5 * Math.PI;
        plane.position.x = 0;
        plane.position.y = 0;
        plane.position.z = 0;

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

        // position and point the camera to the center of the scene
        camera.position.x = -30;
        camera.position.y = 40;
        camera.position.z = 30;
        camera.lookAt(scene.position);

        // add subtle ambient lighting
        var ambientLight = new THREE.AmbientLight(0x0c0c0c);
        scene.add(ambientLight);

        // add spotlight for the shadows
        var spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(-40, 60, -10);
        spotLight.castShadow = true;
        spotLight.shadowMapHeight=4096;
        spotLight.shadowMapWidth=4096;
        scene.add(spotLight);

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

        // call the render function
        var step = 0;

        var controls = new function () {
            this.rotationSpeed = 0.02;
            this.numberOfObjects = scene.children.length;

            this.removeCube = function () {
                var allChildren = scene.children;
                var lastObject = allChildren[allChildren.length - 1];
                if (lastObject instanceof THREE.Mesh) {
                    scene.remove(lastObject);
                    this.numberOfObjects = scene.children.length;
                }
            };

            this.addCube = function () {

                var cubeSize = Math.ceil((Math.random() * 3));
                var cubeGeometry = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);
                var cubeMaterial = new THREE.MeshLambertMaterial({color: Math.random() * 0xffffff});
                var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
                cube.castShadow = true;
                cube.name = "cube-" + scene.children.length;


                // position the cube randomly in the scene

                cube.position.x = -30 + Math.round((Math.random() * planeGeometry.parameters.width));
                cube.position.y = Math.round((Math.random() * 5));
                cube.position.z = -20 + Math.round((Math.random() * planeGeometry.parameters.height));

                // add the cube to the scene
                scene.add(cube);
                this.numberOfObjects = scene.children.length;
            };

            this.outputObjects = function () {
                console.log(scene.children);
            }
        };

        var gui = new dat.GUI();
        gui.add(controls, 'rotationSpeed', 0, 0.5);
        gui.add(controls, 'addCube');
        gui.add(controls, 'removeCube');
        gui.add(controls, 'outputObjects');
        gui.add(controls, 'numberOfObjects').listen();

        render();

        function render() {
            stats.update();

            // rotate the cubes around its axes
            scene.traverse(function (e) {
                if (e instanceof THREE.Mesh && e != plane) {

                    e.rotation.x += controls.rotationSpeed;
                    e.rotation.y += controls.rotationSpeed;
                    e.rotation.z += controls.rotationSpeed;
                }
            });

            // render using requestAnimationFrame
            requestAnimationFrame(render);
            renderer.render(scene, camera);
        }

        function initStats() {

            var stats = new Stats();

            stats.setMode(0); // 0: fps, 1: ms

            // Align top-left
            stats.domElement.style.position = 'absolute';
            stats.domElement.style.left = '0px';
            stats.domElement.style.top = '0px';

            document.getElementById("Stats-output").appendChild(stats.domElement);

            return stats;
        }
    }
    window.onload = init


</script>
</body>
</html>

場景的相關(guān)函數(shù):

Scene.Add():向場景中添加物體
Scene.Remove():在場景中移除物體
Scene.children():獲取場景中的所有子對象的列表
Scene.getChildByName():獲取場景中某個特定名字的子物體

在render函數(shù)中,我們的處理方式和上一章差不讀,只不過在這里對使用scene.traverse()來進(jìn)行一個對場景中的對象進(jìn)行一個遍歷,及對每個子對象都執(zhí)行一次相應(yīng)函數(shù)。
我們也可以使用for循環(huán)來遍歷場景的children這個屬性數(shù)組來達(dá)到相同的結(jié)果。

《場景的特殊效果》

Scene的霧

scene.fog=new THREE.FogExp2(0xffffff,0.015);

注意,使用霧會增加資源使用,降低幀率。

材質(zhì)覆蓋

scene.overrideMaterial=new THREE.MeshLambertMaterial({color:0xffffff});

使用上述函數(shù)將會覆蓋場景中所有材質(zhì)為指定材質(zhì)

《幾何體和網(wǎng)格對象》

在第一章我們用到了如何在場景中添加一個幾何體和網(wǎng)格對象,如添加一個立方體的代碼如下:

var cubeGeometry = new THREE.CubeGeometry(4,4,4);
var cubeMaterial = new THREE.MeshPhongMaterial({color:0xff0000});
var cube=new THREE.Mesh(cubeGeometry,cubeMaterial);
scene.add(cube);

在上述代碼中,我們定義了該網(wǎng)格對象的形狀、幾何結(jié)構(gòu)、外觀、材質(zhì)等屬性,并把這些屬性和一個名為cube的網(wǎng)格對象結(jié)合在一起。

《幾何對象的屬性和函數(shù)》

geometry變量:
geometry變量是三維空間中的點集以及將這些點連接起來的面。(頂點vertice和面face)
例如:一個立方體有8個頂點(8個角),每個頂點的空間坐標(biāo)為一個x,y,z的組合。這些點稱為頂點
一個立方體有6個面,這6個面稱為face。
像在opengl里面定義幾何體一樣,我們可以使用定義頂點和面的方法來定義一個幾何體:

var vertices=[
    new THREE.Vector3(1,3,1),
    new THREE.Vector3(1,3,-1),
    ...
    new THREE.Vector3(-1,-1,1)
];
var faces=[
    new THREE.Face3(0,2,1),
    new THREE.Face3(2,3,1),
    ...
    new THREE.Face3(3,6,4)
];
var geom=new THREE.Geometry();
geom.vertices=vertices;
geom.faces=faces;
geom.computeCentroids();
geom.mergeVertices()();

關(guān)于如何動態(tài)修改幾何體的頂點和面的知識,會在后面講到。

《網(wǎng)格對象的函數(shù)和屬性》

網(wǎng)格對象的主要屬性:
position
Rotation
Scale
TranslateX
TranslateY
TranslateZ
上述屬性與Unity3D API中的Transform的屬性相類似
可以通過直接修改position的值來改變網(wǎng)格物體的位置,網(wǎng)格物體的position其實質(zhì)上是一個THREE.Vector3類型的變量,所以其設(shè)置的方法有如下:

Obj.position.x=1;…
Obj.position=new THREE.Vector3(1,2,3);
Obj.position.set(1,2,3);

在設(shè)置對象位置的過程中,設(shè)置的位置是相對于其父對象的位置而設(shè)置的。比如使用THREE.SceneUtils.createMultiMaterialObject()創(chuàng)建多個不同材質(zhì)的對象時,返回的不僅僅是一個對象,而是一個對象組。如果我們改變其中一個對象的位置的時候,另一個對象不會發(fā)生改變,如果改變這個對象組的位置的時候,其所有子物體都會發(fā)生改變。(父子階層)
對于rotation的操作對象是數(shù)學(xué)中的弧度(rad),一個物體旋轉(zhuǎn)一周的弧度是2*PI。所以我們的旋轉(zhuǎn)操作代碼如下:

Obj.rotation.x=0.5*Math.PI;(旋轉(zhuǎn)0.5π個弧度,即旋轉(zhuǎn)90度)
Obj.rotation.set(0.5*Math.PI,0,0);
Obj.rotation=new THREE.Vector3(0.5*Math.PI,0,0);

上述代碼表示繞著x軸旋轉(zhuǎn)90°的操作。
Scale基本同上。
對于translate函數(shù),使用translate可以改變物體的位置,translate是相對于物體所移動的位移,而非絕對位置(與Unity的Translate類似)。

《相機(jī)》

正交相機(jī)和透視相機(jī)是所有的3D引擎中都存在的2種相機(jī)。對于不同的需求我們選擇使用不同的相機(jī)。
對于透視相機(jī)THREE.PerspectiveCamera主要參數(shù)如下:
Fov(視角場):人類眼鏡的視野大概為180°,一些鳥類有著360°的視野,在游戲中我們通常使用60到90°的視角,而在普通的3D應(yīng)用中我們推薦使用45°的視野。
Aspect(長寬比):長寬比指的是渲染結(jié)果輸出的橫向長度和縱向長度的比值。推薦使用window.innerWidth/window.innerHeight
Near(近視平面)
Far(遠(yuǎn)視平面)

對于正交相機(jī)THREE.OrthographicCamera的主要參數(shù)如下:
Left(左邊界)
Right(右邊界)
Top(上邊界)
Bottom(下邊界)
Near(近視平面)
Far(遠(yuǎn)視平面)
以上一些屬性及其含義可以在OpenGL的官網(wǎng)文檔中找到。

如何讓相機(jī)看向指定位置?
使用camera.lookAt(new THREE.Vector3(x,y,z));函數(shù)做到使相機(jī)看向x,y,z點。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容