Three.js-SceneUtils 도구 류 결합 소 재 를 사용 합 니 다.

37833 단어 ThreeJS 개발
MeshDepthMaterial속성 이 없 기 때문에 재질 외부의 색 을 동적 으로 바 꿀 수 없 지만color도구 류 의 한 방법SceneUtils을 통 해 재질 의 결합 을 통 해 색 의 추 가 를 실현 할 수 있다.모 르 시 면createMultiMaterialObject17-three.js 노트-SceneUtils 도구 류 예제:https://ithanmang.gitee.io/threejs/home/201808/20180806/02-combined-material.html three.js 는 재질 의 결합 을 통 해 새로운 효 과 를 만 들 수 있 습 니 다.SceneUtils라 이브 러 리 파일 을 도입 해 야 합 니 다.이 파일 은 디 렉 터 리SceneUtils.js아래 에 있 습 니 다.파일 가 져 오기
<!--           SceneUtils    -->
<script src="../../libs/examples/js/utils/SceneUtils.js"></script>

SceneUtils 는 세 가지 방법 이 있어 요.
  • createMultiMaterialObject 이 방법 은 여러 가지 소 재 를 조합 하여 하나의examples\js\utils대상 을 되 돌려 줍 니 다.
  • attach 이 방법 은 대상 의 하위 대상 을 부모 대상 에 추가 하 는 것 입 니 다.부모 대상 이 매트릭스 updateMatrixWorld
  • 를 업데이트 해 야 합 니 다.
  • detach 이 방법 은 대상 자 체 를 부모 대상 에서 분리 하여 다시Group에 추가 하 는 것 입 니 다.부모 대상 이 매트릭스 updateMatrix World 를 업데이트 해 야 하기 때문에sceneSceneUtils을 사용 하여 색상 속성 이 없 는createMultiMaterialObject과 다른 색상 속성 이 있 는 소 재 를 결합 시 켜 그 라 데 이 션 효 과 를 실현 할 수 있 습 니 다.색상 추가 도 이 루어 졌 습 니 다.여기에 기본 소 재 를 만 듭 니 다
  • let basicMaterial = new THREE.MeshBasicMaterial({color: this.color});
    basicMaterial.transparent = true;
    //       
    basicMaterial.blending = THREE.MultiplyBlending;
    
    let cube = new THREE.SceneUtils.createMultiMaterialObject(cubeGeometry, [cubeMaterial, basicMaterial]);
    

    주의해 야 할 것 은:1.색상 을 표시 하 는 소 재 는 투명 하 게 열 어야 합 니 다.그렇지 않 으 면 깊이 소 재 는 기본 소재 의 색상 만 볼 수 있 습 니 다.무선 으로 그 라 데 이 션 효 과 를 실현 합 니 다.2.혼합 효 과 를MeshDepthMaterial중첩 혼합 으로 설정 합 니 다.이런 혼합 모드 는 전경 색 과 배경 색 을 중첩 합 니 다.
    예제 코드
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>MeshDepthMaterial     </title>
        <style>
            body {
                margin: 0;
                overflow: hidden; /*    */
            }
        </style>
        <script src="../../libs/build/three-r93.min.js"></script>
        <script src="../../libs/examples/js/libs/dat.gui.min.js"></script>
        <script src="../../libs/examples/js/libs/stats.min.js"></script>
        <script src="../../libs/examples/js/Detector.js"></script>
        <!--           SceneUtils    -->
        <script src="../../libs/examples/js/utils/SceneUtils.js"></script>
    </head>
    <body>
    <script>
    
        let stats = initStats();
        let scene, camera, renderer, guiControls;
    
        //   
        function initScene() {
    
            scene = new THREE.Scene();
            scene.background = new THREE.Color(0x050505);
    
        }
    
        //   
        function initCamera() {
    
            camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 20, 150);
            camera.position.set(-50, 40, 50);
            camera.lookAt(new THREE.Vector3(0, 0, 0));
    
        }
    
        //    
        function initRenderer() {
    
            renderer = new THREE.WebGLRenderer({antialias: true, alpha: true});
            //     
            renderer.setSize(window.innerWidth, window.innerHeight);
            document.body.appendChild(renderer.domElement);
    
        }
    
        //     
        function initGui() {
    
            guiControls = new function () {
    
                this.sceneBackground = scene.background.getStyle();
                this.cameraNear = camera.near;
                this.cameraFar = camera.far;
                this.numberOfObjects = scene.children.length;
    
                this.addCube = function () {
    
                    let cubeSize = Math.ceil(3 + (Math.random() * 3));
                    let cubeGeometry = new THREE.CubeGeometry(cubeSize, cubeSize, cubeSize);
    
                    let cubeMaterial = new THREE.MeshDepthMaterial();
                    let basicMaterial = new THREE.MeshBasicMaterial({color: 0xffffff * Math.random()});
                    basicMaterial.transparent = true;
                    //       
                    basicMaterial.blending = THREE.MultiplyBlending;
    
                    let cube = new THREE.SceneUtils.createMultiMaterialObject(cubeGeometry, [cubeMaterial, basicMaterial]);
    
                    cube.position.x = -60 + Math.round((Math.random() * 100));
                    cube.position.y = Math.round((Math.random() * 10));
                    cube.position.z = -100 + Math.round((Math.random() * 150));
    
                    scene.add(cube);
                    this.numberOfObjects = scene.children.length;
    
                };
    
                this.removeCube = function () {
    
                    let allChildren = scene.children;
                    let lastObject = allChildren[allChildren.length - 1];
    
                    if (lastObject.isMesh) {
    
                        scene.remove(lastObject);
    
                        this.numberOfObjects = scene.children.length;
    
                    }
    
                }
    
            };
    
            let gui = new dat.GUI({width: 300});
    
            gui.addColor(guiControls, 'sceneBackground').onChange(function (e) {
    
                scene.background.setStyle(e);
    
            });
            gui.add(guiControls, 'cameraNear', 5, 30).onChange(function (e) {
    
                camera.near = e;
                console.log("camera near :" + camera.near);
    
            });
    
            gui.add(guiControls, 'cameraFar', 150, 500).onChange(function (e) {
    
                camera.far = e;
                console.log("camera far :" + camera.far);
            });
    
            gui.add(guiControls, 'addCube');
            gui.add(guiControls, 'removeCube');
    
        }
    
        //     
        function initStats() {
    
            let stats = new Stats();
    
            stats.domElement.style.position = 'absolute';
            stats.domElement.style.left = '0px';
            stats.domElement.style.top = '0px';
    
            document.body.appendChild(stats.domElement);
    
            return stats;
        }
    
        //   
        function update() {
    
            stats.update();
            //         ,        gui           
            camera.updateProjectionMatrix();
    
            scene.traverse(function (e) {
    
                if (e.isMesh) {
    
                    e.rotation.x += 0.02;
                    e.rotation.y += 0.02;
                    e.rotation.z += 0.02;
    
                }
    
            });
    
        }
    
        //    
        function init() {
    
            //      ,         
            if (!Detector.webgl) Detector.addGetWebGLMessage();
    
            initScene();
            initCamera();
            initRenderer();
            initGui();
    
            let i = 0;
            while (i < 20) {
    
                guiControls.addCube();
                i++;
            }
    
            window.addEventListener('resize', onWindowResize, false);
        }
    
        //          
        function onWindowResize() {
    
            //           
            camera.aspect = window.innerWidth / window.innerHeight;
    
            //         
            camera.updateProjectionMatrix();
    
            //        
            renderer.setSize(window.innerWidth, window.innerHeight);
    
        }
    
        //     
        function animate() {
    
            requestAnimationFrame(animate);
            renderer.render(scene, camera);
            update();
        }
    
        //         
        window.onload = function () {
    
            init();
            animate();
    
        };
    
    </script>
    </body>
    </html>
    

    좋은 웹페이지 즐겨찾기