位置: IT常识 - 正文
推荐整理分享three.js实现太阳系(three.js gui),希望有所帮助,仅作参考,欢迎阅读内容。
文章相关热门搜索词:three.js gltf,three.js 发光,three.js osgb,three.js dispose,three.js gui,three.js太阳系,three.js dispose,three.js webgl,内容如对您有帮助,希望把文章链接给更多的朋友!
刚开始使用three.js时会不太熟悉,想写一些项目增加理解,网上翻了好多文章,不是画立方体就是画三角形,最后偶然看到这个网站,十分炫酷。我们也许没那么牛逼,但我们可以整个简略版的太阳系来练练手,加强理解,增加熟练度。
实现目标1、绘制宇宙背景。2、添加宇宙星辰。3、绘制行星轨道。4、绘制行星环。5、实现行星自转与公转。6、实现双击行星后镜头的拉近效果(类似cesium的flyTo效果)。7、显示行星描述。
具体效果这里是浏览地址,项目是用vue2开发的,废话少说,我们直接开整!
导入依赖import * as THREE from "three";//导入three.jsimport { OrbitControls } from "three/examples/jsm/controls/OrbitControls"; //导入鼠标控制器import TWEEN from "@tweenjs/tween.js";//导入tween动画构造行星数据我将数据写在了js里面,便于直接导出,当然你也可以写一个json。这里以一个球体(太阳)作为例子,其他类似。
let sun = { name: "太阳",//球体名称 mapImg: sunImg,//球体贴图 size: sunSize,//球体尺寸 position: [0, 0, 0],//位置(x,y,z) rotation: 0.05,//自转速度 revolution: 0,//公转速度 data: { sunDistance: "0km", weight: "1.989e30kg", diameter: "1392000km", rotation: "36day", revolution: "", temp: "5500℃", atmosphere: "氮气、氧气、氩气", msg: "太阳是在大约45.7亿年前在一个坍缩的氢分子云内形成。太阳是太阳系里唯一的恒星,是太阳系的中心天体。" }//描述};其他球体数据构造完后放入数组,导出。
let planetList = [sun, mercury, venus, earth, mars, jupiter, saturn, uranus, neptune, pluto];export default planetList;初始化场景 init() { this.dom = document.getElementById("planetDiv"); //获取dom let width = this.dom.clientWidth; let height = this.dom.clientHeight; scene = new THREE.Scene(); //场景场景 // scene.add(new THREE.AxesHelper(500)); camera = new THREE.PerspectiveCamera(45, width / height, 1, 50000); //创建透视相机(视场、长宽比、近面、远面) camera.position.set(0, 500, 2700); //设置相机位置 camera.lookAt(0, 0, 0); //创建渲染器 this.renderer = new THREE.WebGLRenderer({ antialias: true, //抗锯齿 alpha: true, //透明 }); this.renderer.setClearColor(0x000000, 0.1); //设置场景透明度 this.renderer.setSize(width, height); //设置渲染区域尺寸 this.dom.appendChild(this.renderer.domElement); //将渲染器添加到dom中形成canvas this.createUniverse(); //创建宇宙 this.createStars(); //创建星辰 this.createLight(); //创建光源 //遍历行星数据生成星球及其轨道 this.planetList.forEach((e) => { this.createSphere(e);//创建球体 this.createTrack(e);//创建轨迹 }); this.createOrbitControls(); //创建鼠标控制器 this.render(); //渲染 },创建场景与渲染器,参数需要自己调节,记得将渲染器的antialias与alph打开。
创建宇宙//创建宇宙(球形宇宙) createUniverse() { let universeGeometry = new THREE.SphereGeometry(7000, 100, 100); let universeMaterial = new THREE.MeshLambertMaterial({ //高光材质 map: new THREE.TextureLoader().load(universeImg),//导入宇宙贴图 side: THREE.DoubleSide, //双面显示 }); //宇宙网格 let universeMesh = new THREE.Mesh(universeGeometry, universeMaterial); universeMesh.name = "宇宙"; scene.add(universeMesh);//将宇宙网格添加到场景中 },这里创建背景的方法为这篇文章的第三种创建背景的方法。使用SphereGeometry创建宇宙的几何体,MeshLambertMaterial作为宇宙的材质,记得打开材质的side属性,进行双面显示。
创建星辰//创建星辰 createStars() { const positions = []; const colors = []; //星辰几何体 const starsGeometry = new THREE.BufferGeometry(); //添加星辰的颜色与位置 for (let i = 0; i < 10000; i++) { let vertex = new THREE.Vector3(); vertex.x = Math.random() * 2 - 1; vertex.y = Math.random() * 2 - 1; vertex.z = Math.random() * 2 - 1; positions.push(vertex.x, vertex.y, vertex.z); let color = new THREE.Color(); color.setRGB(255, 255, 255); colors.push(color.r, color.g, color.b); } starsGeometry.setAttribute( "position", new THREE.Float32BufferAttribute(positions, 3) ); starsGeometry.setAttribute( "color", new THREE.Float32BufferAttribute(colors, 3) ); //星辰材质 let starsMaterial = new THREE.PointsMaterial({ map: new THREE.TextureLoader().load(starImg), size: 5, blending: THREE.AdditiveBlending, fog: true, depthTest: false, //(不能与blending一起使用) // depthWrite: false, //(深度写入)防止星辰在球体前面出现黑块 }); //星辰的集合 let starsMesh = new THREE.Points(starsGeometry, starsMaterial); starsMesh.scale.set(7000, 7000, 7000); //设置集合体范围 scene.add(starsMesh); },星辰是若干个THREE.Points构成的,材质是PointsMaterial,几何体是BufferGeometry,在添加星辰到场景中前,记得使用scale.set()设置星辰集合的尺度。
创建光源//创建光源 createLight() { let ambient = new THREE.AmbientLight(new THREE.Color(0xffffff)); //环境光 scene.add(ambient); let pointLight = new THREE.PointLight(new THREE.Color(0xffffff), 2, 1, 0); //点光源 pointLight.visible = true; pointLight.position.set(0, 0, 0); //点光源在原点充当太阳 scene.add(pointLight); //点光源添加到场景中 },这里我将光源设置在太阳的中心,即场景的中心。
创建球体//创建球体 createSphere(data) { //处理特殊球体 if (data.name == "太阳") { this.createSun(data); } else if (data.name == "地球") { this.createEarth(data); } else if (data.name == "金星") { this.createVenus(data); } else if (data.name == "土星") { this.createSaturn(data); } else { //其他球体 let sphereGeometry = new THREE.SphereGeometry(data.size, 100, 100); //球体几何体 //球体材质 let sphereMaterial = new THREE.MeshLambertMaterial({ map: new THREE.TextureLoader().load(data.mapImg), }); let sphereMesh = new THREE.Mesh(sphereGeometry, sphereMaterial); //生成球体网格 sphereMesh.name = data.name; //网格名字 sphereMesh.planetMsg = data; sphereMesh.isPlanet = true; //标识为星球 sphereMesh.angle = 0; //添加初始角度 //球体位置 sphereMesh.position.set( data.position[0],//x data.position[1],//y data.position[2]//z ); scene.add(sphereMesh); //球体添加到场景中 } },这里我将单独处理太阳、地球、金星、土星,其他星球直接通过行星数据进行批量创建。流程均为,创建SphereGeometry,创建MeshLambertMaterial,设置位置、添加到场景。
创建太阳//创建太阳 createSun(data) { let sunGroup = new THREE.Group(); //太阳的组 let sunGeometry = new THREE.SphereGeometry(data.size, 100, 100); //太阳几何体 let sunMaterial = new THREE.MeshLambertMaterial({ //太阳材质 color: new THREE.Color(0xffffff), map: new THREE.TextureLoader().load(data.mapImg), }); let sunMesh = new THREE.Mesh(sunGeometry, sunMaterial); sunGroup.add(sunMesh); //太阳大气几何体 let sunAtmosphereGeometry = new THREE.SphereGeometry( data.size + 8, 100, 100 ); let sunAtmosphereMaterial = new THREE.MeshLambertMaterial({ color: new THREE.Color(0xffffff), transparent: true, opacity: 0.2, }); let sunAtmosphereMesh = new THREE.Mesh( sunAtmosphereGeometry, sunAtmosphereMaterial ); sunGroup.add(sunAtmosphereMesh); sunGroup.name = data.name; //网格名字 sunGroup.planetMsg = data; sunGroup.isPlanet = true; //标识为星球 sunGroup.angle = 0; //添加初始角度 //球体位置 sunGroup.position.set( data.position[0], data.position[1], data.position[2] ); scene.add(sunGroup); },创建太阳需要使用THREE.Group(),将太阳网格sunMesh 添加到组中再将组添加到场景中。这里我们给太阳添加了一层透明球壳作为太阳大气,大气半径需要大于太阳球体,同时太阳大气材质MeshLambertMaterial需要开启透明属性transparent。金星与太阳的创建方法一样,只不过金星大气多添加了贴图材质。
创建地球 //创建地球 createEarth(data) { let earthGroup = new THREE.Group(); //地球的组 let earthGeometry = new THREE.SphereGeometry(data.size, 100, 100); //地球几何体 //地球材质 let earthMaterial = new THREE.MeshPhysicalMaterial({ map: new THREE.TextureLoader().load(data.mapImg), normalScale: new THREE.Vector2(10, 10), //凹凸深度 normalMap: new THREE.TextureLoader().load(earthNormalImg), //法线贴图 }); let earthMesh = new THREE.Mesh(earthGeometry, earthMaterial); //地球网格 earthGroup.add(earthMesh); //将地球网格添加到地球组中 //地球云层几何体 let earthCloudsGeometry = new THREE.SphereGeometry( data.size + 2, 100, 100 ); //地球云层材质 let earthCloudsMaterial = new THREE.MeshLambertMaterial({ color: new THREE.Color(0xffffff), transparent: true, opacity: 0.4, map: new THREE.TextureLoader().load(earthCloudsImg), }); //地球云层网格 let earthCloudsMesh = new THREE.Mesh( earthCloudsGeometry, earthCloudsMaterial ); earthGroup.add(earthCloudsMesh); //将地球云层网格添加到地球组中 //创建月球轨道 let moonTrackGeometry = new THREE.RingBufferGeometry( //圆环几何体 data.size + 40, data.size + 40.2, 100 ); let moonTrackMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff, side: THREE.DoubleSide, }); let moonTrackMesh = new THREE.Mesh(moonTrackGeometry, moonTrackMaterial); moonTrackMesh.rotation.set(0.5 * Math.PI, 0, 0); earthGroup.add(moonTrackMesh); //创建月球 let moonGeometry = new THREE.SphereGeometry(10, 100, 100); let moonMaterial = new THREE.MeshPhysicalMaterial({ map: new THREE.TextureLoader().load(moonImg), normalScale: new THREE.Vector2(10, 10), //凹凸深度 }); let moonMesh = new THREE.Mesh(moonGeometry, moonMaterial); moonMesh.position.set(data.size + 40, 0, 0); earthGroup.add(moonMesh); earthGroup.name = data.name; //网格名字 earthGroup.planetMsg = data; earthGroup.isPlanet = true; //标识为星球 earthGroup.angle = 0; //添加初始角度 //球体位置 earthGroup.position.set( data.position[0], data.position[1], data.position[2] ); scene.add(earthGroup); },创建地球使用的材质为MeshPhysicalMaterial,该材质使用normalMap添加法线贴图与normalScale设置凹凸深度后可使该材质显示出凹凸效果。地球周围有月球,月球轨道使用环形几何体RingBufferGeometry创建,月球使用MeshPhysicalMaterial材质创建,将创建好的月球添加到地球组中,最后将地球组添加到场景中。
创建土星 //创建土星 createSaturn(data) { let saturnGroup = new THREE.Group(); //土星的组 let saturnGeometry = new THREE.SphereGeometry(data.size, 100, 100); //土星几何体 let saturnMaterial = new THREE.MeshLambertMaterial({ map: new THREE.TextureLoader().load(data.mapImg), //土星材质 }); let saturnMesh = new THREE.Mesh(saturnGeometry, saturnMaterial); //土星网格 saturnGroup.add(saturnMesh); //将土星网格添加到地球组中 //创建土星环1 let saturnTrackGeometry1 = new THREE.RingBufferGeometry( //圆环几何体 data.size + 10, data.size + 25, 100 ); let saturnTrackMaterial1 = new THREE.MeshLambertMaterial({ transparent: true, opacity: 0.8, color: 0xc0ad87, side: THREE.DoubleSide, }); let saturnTrackMesh1 = new THREE.Mesh( saturnTrackGeometry1, saturnTrackMaterial1 ); saturnTrackMesh1.rotation.set(0.5 * Math.PI, 0, 0); //创建土星环2 let saturnTrackGeometry2 = new THREE.RingBufferGeometry( //圆环几何体 data.size + 26, data.size + 30, 100 ); let saturnTrackMaterial2 = new THREE.MeshLambertMaterial({ transparent: true, opacity: 0.5, color: 0xc0ad87, side: THREE.DoubleSide, }); let saturnTrackMesh2 = new THREE.Mesh( saturnTrackGeometry2, saturnTrackMaterial2 ); saturnTrackMesh2.rotation.set(0.5 * Math.PI, 0, 0); //创建土星环3 let saturnTrackGeometry3 = new THREE.RingBufferGeometry( //圆环几何体 data.size + 30.1, data.size + 32, 100 ); let saturnTrackMaterial3 = new THREE.MeshLambertMaterial({ transparent: true, opacity: 0.3, color: 0xc0ad87, side: THREE.DoubleSide, }); let saturnTrackMesh3 = new THREE.Mesh( saturnTrackGeometry3, saturnTrackMaterial3 ); saturnTrackMesh3.rotation.set(0.5 * Math.PI, 0, 0); saturnGroup.add(saturnTrackMesh1); //将网格添加到组中 saturnGroup.add(saturnTrackMesh2); saturnGroup.add(saturnTrackMesh3); saturnGroup.name = data.name; //网格名字 saturnGroup.planetMsg = data; saturnGroup.isPlanet = true; //标识为星球 saturnGroup.angle = 0; //添加初始角度 //球体位置 saturnGroup.position.set( data.position[0], data.position[1], data.position[2] ); scene.add(saturnGroup); },土星特点是其土星环,土星环使用环形几何体RingBufferGeometry创建,材质使用MeshLambertMaterial,记得设置属性side: THREE.DoubleSide,双面显示。将土星环都添加到土星组中,最后将土星组添加到场景中。
创建行星轨道 //创建球体轨迹 createTrack(data) { if (data.name == "太阳") { //去除太阳中心由圆环形成的圆形 return; } //创建轨迹 let trackGeometry = new THREE.RingBufferGeometry( //圆环几何体 data.position[0], data.position[0] + 2, 1000 ); //圆环材质 let trackMaterial = new THREE.LineBasicMaterial({ color: 0xffffff, side: THREE.DoubleSide, }); let trackMesh = new THREE.Mesh(trackGeometry, trackMaterial); trackMesh.position.set(0, 0, 0); //轨道位置 trackMesh.rotation.set(0.5 * Math.PI, 0, 0); //旋转轨道至水平 scene.add(trackMesh); },星球轨道的创建与月球轨道的创建一样,使用的几何体也是圆环几何体RingBufferGeometry,除开太阳外其他星球均绘制轨道。
渲染动画 //渲染 render() { //请求动画帧,屏幕每刷新一次调用一次,绑定屏幕刷新频率 this.anId = requestAnimationFrame(this.render); //记录下动画id可用于销毁场景 orbitControls.update(); //鼠标控件实时更新 this.renderer.render(scene, camera); //控制公转 if (this.isRevolution) { this.sphereRevolution(this.planetList); //球体公转 } if (this.isRotation) { this.sphereRotation(this.planetList); //球体自转 } //监听画布双击事件 document.getElementById("planetDiv") && document .getElementById("planetDiv") .addEventListener("dblclick", this.handleDblclick, false); TWEEN.update(); //更新动画 },three.js的动画渲染通常使用请求动画帧requestAnimationFrame来完成。在渲染动画时即可添加各种事件与限制。
球体自转 //球体自转 sphereRotation(data) { scene.children.forEach((e) => { //过滤出星球 if (e.isPlanet) { let planetData = data.filter((d) => d.name == e.name)[0]; if (e.name == "土星") { e.rotation.x = 0.05 * 2 * Math.PI; // return; } //天王星自转轴特殊 if (e.name == "天王星") { e.rotation.z = e.rotation.z + planetData.rotation >= 2 * Math.PI ? 0 : e.rotation.z + planetData.rotation; return; } e.rotation.y = e.rotation.y + planetData.rotation >= 2 * Math.PI ? 0 : e.rotation.y + planetData.rotation; } }); },在场景中过滤出标识为星球的物体执行自转逻辑,自转时值得注意的是土星与天王星的自转,土星自转是x轴角度自增的,天王星是z轴角度自增的,其他星球均为y轴角度变化。
球体公转 //球体公转 sphereRevolution(data) { scene.children.forEach((e) => { //过滤出星球 if (e.isPlanet) { let planetData = data.filter((d) => d.name == e.name)[0]; //获取球体数据 e.angle = e.angle + planetData.revolution >= 2 * Math.PI ? 0 : e.angle + planetData.revolution; e.position.set( planetData.position[0] * Math.sin(e.angle), 0, planetData.position[0] * Math.cos(e.angle) ); } }); },在场景中过滤出标识为星球的物体执行公转逻辑,所有公转行星中金星的公转角是自减的。
实现flyTo //双击事件 handleDblclick(e) { let dom = document.getElementById("planetDiv"); let width = dom.clientWidth; //窗口宽度 let height = dom.clientHeight; //窗口高度 //将鼠标点击位置的屏幕坐标转换成threejs中的标准坐标 this.mouse.x = (e.offsetX / width) * 2 - 1; this.mouse.y = -(e.offsetY / height) * 2 + 1; // 通过鼠标点的位置和当前相机的矩阵计算出raycaster this.raycaster.setFromCamera(this.mouse, camera); //生成星球网格列表 let palnetMeshList = []; scene.children.forEach((p) => { if (p.name !== "") { palnetMeshList.push(p); } }); // 获取raycaster直线和星球网格列表相交的集合 let intersects = this.raycaster.intersectObjects(palnetMeshList); //判断是否点击到虚无的太空 if (intersects.length == 0) { return; } //判断是否是行星 if (intersects[0].object.isPlanet) { this.clickPlanet = intersects[0].object; } else { this.clickPlanet = intersects[0].object.parent; } // console.log(this.clickPlanet); //获取球体半径 let planetR = ""; this.planetList.forEach((e) => { if (e.name == this.clickPlanet.name) { planetR = e.size; } }); //相机新位置 let newP = { x: this.clickPlanet.position.x, y: this.clickPlanet.position.y + planetR, z: this.clickPlanet.position.z + 2.5 * planetR, }; //双击到星球需要停止公转(双击虚空需反转公转状态) if (this.clickPlanet.type !== "Scene") { this.isRevolution = false; this.isRotation = false; //点击后传入参数飞向星球 this.flyTo( camera.position, orbitControls.target, newP, this.clickPlanet.position, 2000 ); } else { this.isRevolution = !this.isRevolution; this.isRotation = !this.isRotation; } }, //飞向对象(旧相机位置,旧对象位置,新相机位置,新对象位置,动画时间,回调) flyTo(oldP, oldT, newP, newT, time, callBack) { if (TWEEN) { let tween = new TWEEN.Tween({ x1: oldP.x, // 相机x y1: oldP.y, // 相机y z1: oldP.z, // 相机z x2: oldT.x, // 控制点的中心点x y2: oldT.y, // 控制点的中心点y z2: oldT.z, // 控制点的中心点z }); tween.to( { x1: newP.x, y1: newP.y, z1: newP.z, x2: newT.x, y2: newT.y, z2: newT.z, }, time ); tween.onUpdate(function (object) { camera.position.set(object.x1, object.y1, object.z1); orbitControls.target.x = object.x2; orbitControls.target.y = object.y2; orbitControls.target.z = object.z2; orbitControls.update(); }); tween.onComplete(function () { callBack && callBack(); }); tween.easing(TWEEN.Easing.Cubic.InOut); tween.start(); } },双击事件击中球体时触发flyTo效果。需要使用three.js的光线投射器THREE.Raycaster(),判断击中的物体是否为指定物体。若判断击中的物体为星球,则使用flyTo效果,否则为击中虚无太空。这里的flyTo效果实现使用了@tweenjs/tween.js中的TWEEN来实现拉近动画效果。
显示行星描述<template> <div class="msg-div"> <div class="top-r"> <!--边角样式--> </div> <div class="bottom-r"></div> <div class="parameter-div"> <div class="name">{{ msg.name }}</div> <div> 距离太阳:<span>{{ data.sunDistance }}</span> </div> <div> 质量:<span>{{ data.weight }}</span> </div> <div> 直径:<span>{{ data.diameter }}</span> </div> <div> 自转:<span>{{ data.rotation }}</span> </div> <div> 公转:<span>{{ data.revolution }}</span> </div> <div> 表面温度:<span>{{ data.temp }}</span> </div> <div> 大气成分:<span>{{ data.atmosphere }}</span> </div> </div> <div class="description"> {{ data.msg }} </div> </div></template><script>import gsap from "gsap";//行星信息显示时使用动画export default { props: { //星球信息 msg: { type: Object, default() { return {}; }, }, }, components: {}, data() { return {}; }, computed: { data() { return this.msg.data; }, }, watch: {}, created() {}, mounted() { this.showMsg(); }, methods: { showMsg() { gsap.fromTo(".msg-div", { x: 200 }, { x: 0, duration: 0.5 }); }, },};</script>在双击击中行星时,取出该行星数据,将该行星数据传递至一个信息显示组件,组件使用gsap.fromTo动画。
源码地址文章省略了很多代码,可以查看项目所有源码
上一篇:day03-CSS
下一篇:【HDLBits刷题笔记】13 Finite State Machines(刷题笔贴吧)
友情链接: 武汉网站建设