【Three.js】五、three.js中的材质——Material

three.js中的材质就是几何体表面的材料。所有材质均继承自Material。

一、Material

材质基类,Material拥有的属性,其子类均可使用。

1.1 Material属性

属性 说明
color 材质颜色
transparent 定义此材质是否透明,该值设为true才可以使用透明
alphaTest 不透明度低于此值,则不会渲染材质。默认值为0。
opacity 透明度
side 材质被应用与哪一面,正面(TREE.FrontSide)or反面(THREE.BackSide)or两面(DoubleSide)
depthTest 是否在渲染此材质时启用深度测试。默认为 true。
depthWrite 渲染此材质是否对深度缓冲区有任何影响。默认为true。
fog 材质是否受雾的影响
vertexColors 是否使用顶点着色。默认值为THREE.NoColors。 其他选项有THREE.VertexColors 和 THREE.FaceColors。

以上属性可在MeshBasicMaterial中的示例中看到展示效果

二、LineBasicMaterial

一种用于绘制线框样式几何体的材质。

LineBasicMaterial相关属性(color/light除外)只能使用CanvasRenderer渲染器渲染时才有效。CanvasRenderer在r98版本之后已被移除。

import '../../stylus/index.styl'

import * as THREE from 'three'
import * as dat from 'dat.gui'
import {initStats, initTrackballControls} from "../../util/util";

function init(){
    let stats = initStats();
    let scene = new THREE.Scene();
    scene.background = new THREE.Color( 0xf0f0f0 );
    let camera = new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,0.1,10000);
    let renderer = new THREE.WebGLRenderer({antialias: true});
    camera.position.set(-30, 60,70);
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio( window.devicePixelRatio );
    scene.add(camera);
    document.body.appendChild(renderer.domElement);

    // 创建曲线
    let curve = new THREE.CatmullRomCurve3([
        new THREE.Vector3( -10, 0, 10 ),
        new THREE.Vector3( -5, 5, 5 ),
        new THREE.Vector3( 0, 0, 0 ),
        new THREE.Vector3( 5, -5, 5 ),
        new THREE.Vector3( 10, 0, 10 )
    ],true);
    let points = curve.getPoints(500);
    let lineGeometry = new THREE.BufferGeometry().setFromPoints(points);
    let lineMaterial = new THREE.LineBasicMaterial( {
        color: 0xff0000
    } );
    let line = new THREE.Line(lineGeometry, lineMaterial);
    line.position.set(0,0,0);
    scene.add(line);
    camera.lookAt(scene.position);

    let trackballControl = initTrackballControls(camera, renderer);
    function render(){
        stats.update();
        trackballControl.update();
        requestAnimationFrame(render);
        renderer.render(scene, camera);
    }
    render();
}
init();

完整示例(src/pages/three_LineBasicMaterial_demo):https://github.com/MAXLZ1/threejs_demo

三、LineDashedMaterial

一种用于绘制虚线线框样式几何体的材质。

3.1 LineDashedMaterial属性

属性 说明
color 线条颜色
dashSize 虚线的大小,是指破折号和间隙之和。默认值为 3
gapSize 间隙的大小,默认值为 1
scale 线条中虚线部分的占比。默认值为 1

示例:

import '../../stylus/index.styl'

import * as THREE from 'three'
import * as dat from 'dat.gui'
import {initStats, initTrackballControls} from "../../util/util";

function init(){
    let stats = initStats();
    let scene = new THREE.Scene();
    scene.background = new THREE.Color( 0xf0f0f0 );
    let camera = new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,0.1,10000);
    let renderer = new THREE.WebGLRenderer({antialias: true});
    camera.position.set(-30, 60,70);
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio( window.devicePixelRatio );
    scene.add(camera);
    document.body.appendChild(renderer.domElement);

    // 创建曲线
    let curve = new THREE.CatmullRomCurve3([
        new THREE.Vector3( -10, 0, 10 ),
        new THREE.Vector3( -5, 5, 5 ),
        new THREE.Vector3( 0, 0, 0 ),
        new THREE.Vector3( 5, -5, 5 ),
        new THREE.Vector3( 10, 0, 10 )
    ],true);
    let points = curve.getPoints(500);
    let lineGeometry = new THREE.BufferGeometry().setFromPoints(points);
    let lineMaterial = new THREE.LineDashedMaterial( {
        color: 0xff0000,
        dashSize: 1,
        gapSize: 0.5,
        scale: 1
    } );
    let line = new THREE.Line(lineGeometry, lineMaterial);
    line.computeLineDistances();
    line.position.set(0,0,0);
    scene.add(line);
    camera.lookAt(scene.position);
    let gui = new dat.GUI();
    let controls = {
        color: lineMaterial.color.getStyle(),
        dashSize: lineMaterial.dashSize,
        gapSize: lineMaterial.gapSize,
        scale: lineMaterial.scale
    };
    gui.addColor(controls, 'color').onChange(value => lineMaterial.color.setStyle(value));
    gui.add(controls, 'dashSize', 0, 10).onChange(value => lineMaterial.dashSize = value);
    gui.add(controls, 'gapSize', 0, 10).onChange(value => lineMaterial.gapSize = value);
    gui.add(controls, 'scale', 0, 10).onChange(value => lineMaterial.scale = value);
    let trackballControl = initTrackballControls(camera, renderer);
    function render(){
        stats.update();
        trackballControl.update();
        requestAnimationFrame(render);
        renderer.render(scene, camera);
    }
    render();
}
init();

在这里插入图片描述
完整示例(src/pages/three_LineDashedMaterial_demo):https://github.com/MAXLZ1/threejs_demo

四、MeshBasicMaterial

一个以简单着色(平面或线框)方式来绘制几何体的材质。这种材质不受光照的影响。

4.1 MeshBasicMaterial属性

属性 说明
wireframe 将几何体渲染为线框。默认值为false(即渲染为平面多边形)
map 颜色贴图
envMap 环境贴图
reflectivity 环境贴图对表面的影响程度,默认值为1,有效范围介于0(无反射)和1(完全反射)之间
refractionRatio 空气的折射率(约为1)除以材质的折射率,默认0.98,不能超过1
import '../../stylus/index.styl'
import * as THREE from 'three'
import * as dat from 'dat.gui'
import brickImage from '../../assets/images/brick_roughness.jpg'
import nx from '../../assets/images/nx.jpg';
import ny from '../../assets/images/ny.jpg';
import nz from '../../assets/images/nz.jpg';
import px from '../../assets/images/px.jpg';
import py from '../../assets/images/py.jpg';
import pz from '../../assets/images/pz.jpg';
import {initStats, initTrackballControls, initThree} from "../../util/util";
import {
    BackSide,
    CubeRefractionMapping,
    DoubleSide,
    FrontSide,
    RepeatWrapping, RGBFormat,
    TextureLoader
} from "../../libs/three.module";

function init(){
    let stats = initStats();
    let {camera, scene, renderer} = initThree({
        sceneOption:{
            color: 0x444444
        }
    });

    let ambientLight = new THREE.AmbientLight(0xffffff);
    scene.add(ambientLight);
    let fog = new THREE.Fog(0xff0000, 0, 200);
    scene.fog = fog;
    // 创建环形管道
    let torusGeometry = new THREE.TorusKnotGeometry(10, 3, 100, 16);
    let torusMaterial = new THREE.MeshBasicMaterial({
        color: 0xffff00,
        skinning: true
    });
    let torus = new THREE.Mesh(torusGeometry, torusMaterial);
    scene.add(torus);
    // 创建贴图加载器
    let textureLoader = new THREE.TextureLoader();
    let cubeTextureLoader = new THREE.CubeTextureLoader();
    let maps = (function(){
        // 创建贴图
        let bricks = textureLoader.load(brickImage);
        bricks.wrapS = RepeatWrapping;
        bricks.wrapT = RepeatWrapping;
        bricks.repeat.set(9,1);
        return {
            none: null,
            bricks
        }
    })();

    let envMaps = (function(){
        let urls = [px, nx, py, ny, pz, nz];
        let reflection = cubeTextureLoader.load(urls);
        reflection.format = RGBFormat;
        let refraction = cubeTextureLoader.load(urls);
        refraction.format = RGBFormat;
        refraction.mapping = CubeRefractionMapping;
        return {
            none: null,
            reflection,
            refraction
        }
    })();

    let gui = new dat.GUI();
    let controls = {
        color: torusMaterial.color.getStyle(),
        alphaTest: torusMaterial.alphaTest,
        transparent: torusMaterial.transparent,
        opacity: torusMaterial.opacity,
        side: torusMaterial.side,
        depthTest:torusMaterial.depthTest,
        depthWrite: torusMaterial.depthWrite,
        fog: torusMaterial.fog,
        vertexColors: torusMaterial.vertexColors,
        wireframe: torusMaterial.wireframe,
        envMap: Object.keys(envMaps)[0],
        map: Object.keys(maps)[0],
        reflectivity: torusMaterial.reflectivity,
        refractionRatio: torusMaterial.refractionRatio
    };
    let fogControls = {
        fog: scene.fog != null,
        color: fog.color.getStyle()
    };
    let fogGui = gui.addFolder('THREE.Fog');
    let basicGui = gui.addFolder('Material');
    let selfGui = gui.addFolder('MeshBasicMaterial');
    let contains = {
        side: {
            'THREE.FrontSide': THREE.FrontSide,
            'THREE.BackSide': THREE.BackSide,
            'THREE.DoubleSide': THREE.DoubleSide
        },
        vertexColors: {
            'THREE.NoColors':THREE.NoColors,
            'THREE.VertexColors': THREE.VertexColors,
            'THREE.FaceColors': THREE.FaceColors
        }
    };
    fogGui.add(fogControls, 'fog').onChange(value => value ? scene.fog = fog : scene.fog = null);
    fogGui.addColor(fogControls, 'color').onChange(value => fog.color.setStyle(value));
    basicGui.addColor(controls, 'color').onChange(value => torusMaterial.color.setStyle(value));
    basicGui.add(controls, 'transparent').onChange(value => torusMaterial.transparent = value);
    basicGui.add(controls, 'alphaTest', 0, 1).onChange(value => torusMaterial.alphaTest = value);
    basicGui.add(controls, 'opacity', 0, 1).onChange(value => torusMaterial.opacity = value);
    basicGui.add(controls, 'fog').onChange(value => {
        torusMaterial.fog = value;
        torusMaterial.needsUpdate = true;
    });
    basicGui.add(controls, 'side', contains.side).onChange(value => {
        // 这里必须parseInt?
        torusMaterial.side = parseInt(value);
        torusMaterial.needsUpdate = true;
    });
    basicGui.add(controls, 'depthTest').onChange(value => torusMaterial.depthTest = value);
    basicGui.add(controls, 'depthWrite').onChange(value => torusMaterial.depthWrite = value);
    basicGui.add(controls, 'vertexColors',contains.vertexColors).onChange(value => {
        torusMaterial.vertexColors = parseInt(value);
        torusMaterial.needsUpdate = true;
    });
    selfGui.add(controls, 'wireframe').onChange(value => torusMaterial.wireframe = value);
    selfGui.add(controls, 'map', Object.keys(maps)).onChange(value =>{
        torusMaterial.map = maps[value];
        torusMaterial.needsUpdate = true;
    });
    selfGui.add(controls, 'envMap', Object.keys(envMaps)).onChange(value => {
        torusMaterial.envMap = envMaps[value];
        torusMaterial.needsUpdate = true;
    });
    selfGui.add(controls, 'reflectivity', 0, 1).onChange(value => torusMaterial.reflectivity = value);
    selfGui.add(controls, 'refractionRatio', 0, 1).onChange(value => torusMaterial.refractionRatio = value);
    let trackballControls = initTrackballControls(camera, renderer);
    render();
    function render(){
        stats.update();
        trackballControls.update();
        torus.rotation.x += 0.005;
        torus.rotation.y += 0.005;
        torus.rotation.z += 0.005;
        requestAnimationFrame(render);
        renderer.render(scene, camera);
    }
}
init();

完整示例(src/pages/three_MeshBasicMaterial_demo):https://github.com/MAXLZ1/threejs_demo
在这里插入图片描述

五、MeshDepthMaterial

一种按深度绘制几何体的材质。深度基于相机远近平面。白色最近,黑色最远。

import '../../stylus/index.styl'

import {initStats,initThree,initTrackballControls} from "../../util/util";
import * as THREE from 'three'
import * as dat from 'dat.gui'

function init(){
    let {camera, scene, renderer} = initThree({
        sceneOption:{
            color: 0x444444
        }
    });
    camera.near = 15;
    camera.updateProjectionMatrix();
    let stats = initStats();

    let torusGeometry = new THREE.TorusKnotGeometry(10,3, 100, 16);
    let torusMaterial = new THREE.MeshDepthMaterial();
    let torus = new THREE.Mesh(torusGeometry, torusMaterial);
    scene.add(torus);

    let gui = new dat.GUI();
    let controls = {
        near: camera.near,
        far: camera.far
    };
    let cameragui = gui.addFolder('camera');
    cameragui.add(controls,'near', 0, 50).onChange(value => {
        camera.near = value;
        camera.updateProjectionMatrix()
    });
    cameragui.add(controls, 'far', 0, 1000).onChange(value => {
        camera.far = value;
        camera.updateProjectionMatrix();
    });

    let trackballControls = initTrackballControls(camera, renderer);
    render();
    function render(){
        stats.update();
        trackballControls.update();
        requestAnimationFrame(render);
        renderer.render(scene, camera);
    }
}
init();

在这里插入图片描述
完整示例(src/pages/three_MeshDepthMaterial_demo):https://github.com/MAXLZ1/threejs_demo

六、MeshLambertMaterial

一种非光泽表面的材质,没有镜面高光。
该材质使用基于非物理的Lambertian模型来计算反射率。 这可以很好地模拟一些表面(例如未经处理的木材或石材),但不能模拟具有镜面高光的光泽表面(例如涂漆木材)

import '../../stylus/index.styl'

import {initStats,initThree,initTrackballControls} from "../../util/util";
import * as THREE from 'three'
import * as dat from 'dat.gui'

function init(){
    let {camera, scene, renderer} = initThree({
        sceneOption:{
            color: 0x444444
        }
    });
    camera.near = 15;
    camera.updateProjectionMatrix();
    let stats = initStats();

    let spotLight = new THREE.SpotLight(0xffffff);
    spotLight.position.set(-70, 60, 0);
    scene.add(spotLight);

    let torusGeometry = new THREE.TorusKnotGeometry(10,3, 100, 16);
    let torusMaterial = new THREE.MeshLambertMaterial({
        color: 0x0000ff
    });
    let torus = new THREE.Mesh(torusGeometry, torusMaterial);
    torus.castShadow = true;
    scene.add(torus);

    let gui = new dat.GUI();
    let controls = {
        near: camera.near,
        far: camera.far
    };
    let cameragui = gui.addFolder('camera');
    cameragui.add(controls,'near', 0, 50).onChange(value => {
        camera.near = value;
        camera.updateProjectionMatrix()
    });
    cameragui.add(controls, 'far', 0, 1000).onChange(value => {
        camera.far = value;
        camera.updateProjectionMatrix();
    });

    let trackballControls = initTrackballControls(camera, renderer);
    render();
    function render(){
        stats.update();
        trackballControls.update();
        torus.rotation.x += 0.01;
        torus.rotation.y += 0.01;
        torus.rotation.z += 0.01;
        requestAnimationFrame(render);
        renderer.render(scene, camera);
    }
}
init();
发布了106 篇原创文章 · 获赞 10 · 访问量 2万+
展开阅读全文

threejs多面体贴图加纹理,貌似只改变了颜色,求大神指点!

06-20

``` // 鼠标点击 var outlineMesh; document.addEventListener("mousedown", onDocumentMouseDown, false); init(); animate(); function init() { scr(); objects(); lights(); addfloor(); others(); } // 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); function lights() { var ambientLight = new THREE.AmbientLight(0xffffff, 0.3); scene.add(ambientLight); var pointLight = new THREE.PointLight(0xffffff, 0.1); // scene.add(pointLight); // var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000); var pointLight = new THREE.PointLight(0xffffff, 1); // scene.add(pointLight); camera.add(pointLight); } function objects() { // loadcontainer(); addHospital() } function addHospital() { var hospital = createHospital() // hospital.position.y = 20 scene.add(hospital) } function createHospital() { var hospital = new THREE.Object3D() var frontMainCoords = [ [0, -20], [-30, 0], [0, 20], [30, 0], ] var frontMainShape = utils.makeShape(frontMainCoords) var frontMainGeometry = utils.makeExtrudeGeometry(frontMainShape, 20) var frontMainMaterial = new THREE.MeshPhongMaterial({ map: textures.window() }) // var phongmaterial = new THREE.MeshPhongMaterial({color: 0x677784, transparent: true, opacity: 0.85}); // var phongmes = new THREE.Mesh(frontMainMaterial, phongmaterial); frontMainMaterial.map.repeat.set(0.1, 0.04) var alldate = [] //楼层总列表 for(var i=0;i<6;i++){ /* var frontMain = new THREE.Mesh(frontMainGeometry, frontMainMaterial) hospital.add(frontMain) renderScene()*/ var obj = "sta"+i; alldate.push(obj) } var layerList1 = [] var layerList2 = [] for(var j=0;j<5;j++){ var onedata = new THREE.Mesh(frontMainGeometry, frontMainMaterial); // var onedata =createMesh(frontMainGeometry, "stone.jpg"); hospital.add(onedata); layerList1.push(onedata) } for(var j=5;j<alldate.length;j++){ // var onedata =createMesh(frontMainGeometry, "stone.jpg"); var onedata = new THREE.Mesh(frontMainGeometry, frontMainMaterial); hospital.add(onedata); layerList2.push(onedata) } function createMesh(geom, imageFile) { // var texture = var mat = new THREE.MeshPhongMaterial(); mat.normalMap = new THREE.TextureLoader().load("/seismis/js/3djs/assets/textures/general/" + imageFile); // mat.specular = new THREE.Color(0xffffff); mat.needsUpdate = true; mat.shininess = 10; var mesh = new THREE.Mesh(geom, mat); return mesh; } //中间立体图形 // var polyhedron1 = createMesh(cubeGeometry, "stone.jpg"); renderScene(); var step1 = 0; var step2 = 0; function renderScene() { step1 += 0.1; for(var i=0;i<layerList1.length;i++){ var frontMain = layerList1[i]; frontMain.position.x = 0 + ( (2+i) * (Math.cos(step1))); frontMain.position.y = 0+i*20 + ( 2 * Math.abs(Math.sin(step1))); frontMain.position.z = 0 + ( (2+i) * (Math.cos(step1))); } step2 += 0.1; for(var k=0;k<(layerList2.length);k++){ var frontMain = layerList2[k]; frontMain.position.x = 0 + ( (2+k+5) * (Math.cos(step2))); frontMain.position.y = 0+(k+5)*20 + ( 2 * Math.abs(Math.sin(step2))); frontMain.position.z = 0 + ( (2+k+5) * (Math.cos(step2))); } requestAnimationFrame(renderScene); renderer.render(scene, camera); } // call the render function var step = 0; initModel() function initModel() { //辅助工具 var helper = new THREE.AxisHelper(10); scene.add(helper); var cubeGeometry = new THREE.Geometry(); //创建立方体的顶点 var vertices = [ new THREE.Vector3(0, 0, 20), //v0 new THREE.Vector3(30, 0, 0), //v1 new THREE.Vector3(0, 0,-20), //v2 new THREE.Vector3(-30, 0, 0), //v3 new THREE.Vector3(-30,220,0), //v4 new THREE.Vector3(-22,220,10), //v5 new THREE.Vector3(22,220,10), //v6 new THREE.Vector3(30,220,0), //v7 new THREE.Vector3(22,220,-10), //v8 new THREE.Vector3(-22,220,-10), //v9 ]; cubeGeometry.vertices = vertices; //创建立方的面 var faces=[ new THREE.Face3(0,1,2), new THREE.Face3(0,2,3), new THREE.Face3(3,0,5), new THREE.Face3(3,5,4), new THREE.Face3(3,4,9), new THREE.Face3(3,9,2), new THREE.Face3(2,9,8), new THREE.Face3(8,1,2), new THREE.Face3(8,7,1), new THREE.Face3(6,1,7), new THREE.Face3(6,0,1), new THREE.Face3(0,6,5), new THREE.Face3(5,6,7), new THREE.Face3(5,7,8), new THREE.Face3(5,8,9), new THREE.Face3(5,9,4), ]; cubeGeometry.faces = faces; //生成法向量 cubeGeometry.computeFaceNormals(); function createMesh(geom, imageFile) { // var texture = var mat = new THREE.MeshPhongMaterial(); mat.map = new THREE.TextureLoader().load("/seismis/js/3djs/assets/textures/general/" + imageFile); // mat.specular = new THREE.Color(0xffffff); mat.needsUpdate = true; mat.shininess = 10; var mesh = new THREE.Mesh(geom, mat); return mesh; } //中间立体图形 // var polyhedron1 = createMesh(cubeGeometry, "stone.jpg"); // scene.add(polyhedron1); /* var frontMainMaterial = new THREE.MeshPhongMaterial({ map: textures.window() }) frontMainMaterial.map.repeat.set(0.01, 0.04)*/ var polyhedron1 = createMesh(cubeGeometry, "bathroom-normal.jpg"); polyhedron1.position.x = 0; polyhedron1.position.y = 120; polyhedron1.position.z = 0; scene.add(polyhedron1); /* var textureLoader = new THREE.TextureLoader(); textureLoader.load( "/seismis/js/3djs/assets/textures/general/bathroom-normal.jpg", function( texture ){ // 加载法向贴图 textureLoader.load("/seismis/js/3djs/assets/textures/general/bathroom-normal.jpg", function( normalTexture ){ var geometry = new THREE.BoxGeometry( 50, 50, 50 ); var material = new THREE.MeshBasicMaterial({ map: texture, normalMap: normalTexture // 只要将法向贴图赋给材质的normalMap属性即可 }); mesh = new THREE.Mesh( geometry, material ); scene.add( mesh ); } ); });*/ //12面体 /* var frontMainMaterial = new THREE.MeshPhongMaterial({ map: textures.window() }) var polyhedron2 = new THREE.Mesh(new THREE.IcosahedronGeometry(150, 0), frontMainMaterial); // var polyhedron2 = createMesh(new THREE.IcosahedronGeometry(50, 0), "stone.jpg"); polyhedron2.position.x = 112; scene.add(polyhedron2);*/ var cubeGeometry1 = new THREE.Geometry(); //创建立方体的顶点 var vertices = [ new THREE.Vector3(-30,0,0), //v4 0 new THREE.Vector3(-22,0,10), //v5 1 new THREE.Vector3(-22,0,-10), //v9 2 new THREE.Vector3(-30,35,0) //v10 3 ]; cubeGeometry1.vertices = vertices; //创建立方的面 var faces=[ new THREE.Face3(0,1,3), new THREE.Face3(3,2,0), new THREE.Face3(2,0,1), new THREE.Face3(1,2,3) ]; cubeGeometry1.faces = faces; //生成法向量 cubeGeometry1.computeFaceNormals(); var cubeMaterial = new THREE.MeshLambertMaterial({color: 0x6a5e74}); cube = new THREE.Mesh(cubeGeometry1, cubeMaterial); cube.position.x = 0; cube.position.y = 340; cube.position.z = 0; scene.add(cube); var cubeGeometry2 = new THREE.Geometry(); //创建立方体的顶点 var vertices = [ new THREE.Vector3(30,0,0), //v7 0 new THREE.Vector3(22,0,10), //v6 1 new THREE.Vector3(22,0,-10), //v8 2 new THREE.Vector3(30,35,0) //v11 3 ]; cubeGeometry2.vertices = vertices; //创建立方的面 var faces=[ new THREE.Face3(0,2,1), new THREE.Face3(2,1,3), new THREE.Face3(3,1,0), new THREE.Face3(3,0,2), ]; cubeGeometry2.faces = faces; //生成法向量 cubeGeometry1.computeFaceNormals(); var cubeMaterial = new THREE.MeshLambertMaterial({color: 0x6a5e74}); cube2 = new THREE.Mesh(cubeGeometry2, cubeMaterial); cube2.position.x = 0; cube2.position.y = 340; cube2.position.z = 0; scene.add(cube2); //顶部 var cubeGeometry3 = new THREE.Geometry(); //创建立方体的顶点 var vertices = [ new THREE.Vector3(-27,0,4), // 0 new THREE.Vector3(-27,0,-4), // 1 new THREE.Vector3(-30,11,0), // 2 new THREE.Vector3(30,11,0), // 3 new THREE.Vector3(27,0,4), // 4 new THREE.Vector3(27,0,-4), // 5 ]; cubeGeometry3.vertices = vertices; //创建立方的面 var faces=[ new THREE.Face3(0,2,1), new THREE.Face3(1,2,3), new THREE.Face3(1,3,5), new THREE.Face3(3,2,0), new THREE.Face3(3,0,4), new THREE.Face3(3,4,5), ]; cubeGeometry3.faces = faces; //生成法向量 cubeGeometry1.computeFaceNormals(); var cubeMaterial = new THREE.MeshLambertMaterial({color: 0x6a5e74}); cube2 = new THREE.Mesh(cubeGeometry3, cubeMaterial); cube2.position.x = 0; cube2.position.y = 364; cube2.position.z = 0; scene.add(cube2); } function render() { // stats.update(); polyhedron.rotation.y = step += 0.01; // render using requestAnimationFrame requestAnimationFrame(render); webGLRenderer.render(scene, camera); } return hospital } function createWindow() { var windowObj = new THREE.Object3D() var glassGeometry = new THREE.PlaneGeometry(20, 20) var glass = utils.makeMesh('phong', glassGeometry, 0x6a5e74) windowObj.add(glass) var windowBorderGeometry = new THREE.BoxBufferGeometry(22, 2, 2) var windowBorder = utils.makeMesh('phong', windowBorderGeometry, 0xffffff) var windowBorderTop = windowBorder.clone() windowBorderTop.position.y = 10 windowObj.add(windowBorderTop) var windowBorderBottom = windowBorder.clone() windowBorderBottom.position.y = -10 windowObj.add(windowBorderBottom) var windowBorderLeft = windowBorder.clone() windowBorderLeft.rotation.z = 0.5 * Math.PI windowBorderLeft.position.x = -10 windowObj.add(windowBorderLeft) var windowBorderRight = windowBorderLeft.clone() windowBorderRight.position.x = 10 windowObj.add(windowBorderRight) return windowObj } function loadcontainer() { var onProgress = function (xhr) { if (xhr.lengthComputable) { var percentComplete = xhr.loaded / xhr.total * 100; console.log(Math.round(percentComplete, 2) + '% downloaded'); } }; var onError = function (xhr) { }; var mtlLoader = new THREE.MTLLoader(); mtlLoader.load('/seismis/js/js/objs/5.mtl', function (materials) { materials.preload(); var loader = new THREE.OBJLoader(); loader.setMaterials(materials); loader.load('/seismis/js/js/objs/5.obj', function (object) { object.traverse(function (child) { if (child instanceof THREE.Mesh) { child.material.transparent = true; child.material.opacity = 1; if (child.material instanceof Array) { for (var i = 0, length = child.material.length; i < length; i++) child.material[i].transparent = true; } } }); // for (var i = 0; i < 3; i++) { var temp = object.clone(); // temp.position.set(-100 + 300 * i, 150, 0); temp.position.set(0 , 0, 0); scene.add(temp); // } }, onProgress, onError); }) } function loadmale1() { var onProgress = function (xhr) { if (xhr.lengthComputable) { var percentComplete = xhr.loaded / xhr.total * 100; console.log(Math.round(percentComplete, 2) + '% downloaded'); } }; var onError = function (xhr) { }; THREE.Loader.Handlers.add(/\.dds$/i, new THREE.DDSLoader()); var mtlLoader = new THREE.MTLLoader(); mtlLoader.setPath('/seismis/js/js/objs/male02/'); mtlLoader.load('male02.mtl', function (materials) { console.log(materials); materials.preload(); var objLoader = new THREE.OBJLoader(); objLoader.setMaterials(materials); objLoader.setPath('/seismis/js/js/objs/male02/'); objLoader.load('male02.obj', function (object) { object.position.y = 10; scene.add(object); }, onProgress, onError); }); } // 没有考虑group,所以通过obj加载的物体无法点选 function getMeshs() { var meshs = []; for (var i = 0, length = scene.children.length; i < length; i++) { if (scene.children[i] instanceof THREE.Mesh && scene.children[i].geometry instanceof THREE.BoxGeometry) { meshs.push(scene.children[i]); } } return meshs; } function onDocumentMouseDown(e) { e.preventDefault(); rotate = false; //将鼠标点击位置的屏幕坐标转成threejs中的标准坐标,具体解释见代码释义 var mouse = {}; mouse.x = (e.clientX / window.innerWidth) * 2 - 1; mouse.y = -(e.clientY / window.innerHeight) * 2 + 1; //新建一个三维单位向量 假设z方向就是0.5 //根据照相机,把这个向量转换到视点坐标系 var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5).unproject(camera); console.log(vector); var sub = vector.sub(camera.position); console.log(sub); var param2 = sub.normalize(); var raycaster = new THREE.Raycaster(camera.position, param2); console.log("---------------------------------------------"); //射线和模型求交,选中一系列直线 var intersects = raycaster.intersectObjects(getMeshs()); if (intersects.length > 0) { //选中第一个射线相交的物体 scene.remove(outlineMesh); var SELECTED = intersects[0].object; var outlineMaterial2 = new THREE.MeshBasicMaterial({color: 0x00ff00, side: THREE.BackSide}); outlineMesh = new THREE.Mesh(SELECTED.geometry.clone(), outlineMaterial2); outlineMesh.position.set(SELECTED.position.x, SELECTED.position.y, SELECTED.position.z); outlineMesh.scale.multiplyScalar(1.05); scene.add(outlineMesh); } } ``` 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字50 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览