Three.js進階篇之7 - 3D宇宙特效

allenjiao發表於2018-03-15
[html] view plain copy
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <meta charset="utf-8">  
  5. <style>  
  6. body {margin: 0;}  
  7. body, html {overflow: hidden;}  
  8. body, html, .canvasbox {width: 100%;height: 100%;}  
  9. /* 座標系 */  
  10. .zuobiaoxi {position: absolute;display: table;right: 3px;top: 3px;font-size: 12px;z-index: 1;}  
  11. .zuobiaoxi, .zuobiaoxi h6 {color: #fff;}  
  12. .zuobiaoxi h6, .zuobiaoxi p {margin: 2px 0;}  
  13. .zuobiaoxi h6 {font-size: 12px;font-weight: normal;}  
  14. </style>  
  15. </head>  
  16. <body>  
  17. <div class="canvasbox" id="canvasbox"></div>  
  18. <div class="zuobiaoxi">  
  19.     <h6>攝像機座標</h6>  
  20.     <p>X:<span id="zuobiao-x"></span></p>  
  21.     <p>Y:<span id="zuobiao-y"></span></p>  
  22.     <p>Z:<span id="zuobiao-z"></span></p>  
  23. </div>  
  24. <script src="https://cdn.bootcss.com/three.js/r76/three.min.js"></script>  
  25. <script src="https://cdn.bootcss.com/stats.js/r16/Stats.min.js"></script>  
  26. <script>/*控制攝像機的外掛*/  
  27. /**  
  28.  * @author qiao / https://github.com/qiao  
  29.  * @author mrdoob / http://mrdoob.com  
  30.  * @author alteredq / http://alteredqualia.com/  
  31.  * @author WestLangley / http://github.com/WestLangley  
  32.  * @author erich666 / http://erichaines.com  
  33.  */  
  34. // This set of controls performs orbiting, dollying (zooming), and panning. Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).     Orbit - left mouse / touch: one finger move    Zoom - middle mouse, or mousewheel / touch: two finger spread or squish    Pan - right mouse, or arrow keys / touch: three finter swipe  
  35. THREE.OrbitControls=function(object,domElement){this.object=object;this.domElement=(domElement!==undefined)?domElement:document;this.enabled=true;this.target=new THREE.Vector3();this.minDistance=0;this.maxDistance=Infinity;this.minZoom=0;this.maxZoom=Infinity;this.minPolarAngle=0;this.maxPolarAngle=Math.PI;this.minAzimuthAngle= -Infinity;this.maxAzimuthAngle=Infinity;this.enableDamping=false;this.dampingFactor=0.25;this.enableZoom=true;this.zoomSpeed=1.0;this.enableRotate=true;this.rotateSpeed=1.0;this.enablePan=true;this.keyPanSpeed=7.0;this.autoRotate=false;this.autoRotateSpeed=2.0;this.enableKeys=true;this.keys={LEFT:37,UP:38,RIGHT:39,BOTTOM:40};this.mouseButtons={ORBIT:THREE.MOUSE.LEFT,ZOOM:THREE.MOUSE.MIDDLE,PAN:THREE.MOUSE.RIGHT};this.target0=this.target.clone();this.position0=this.object.position.clone();this.zoom0=this.object.zoom;this.getPolarAngle=function(){return phi};this.getAzimuthalAngle=function(){return theta};this.reset=function(){scope.target.copy(scope.target0);scope.object.position.copy(scope.position0);scope.object.zoom=scope.zoom0;scope.object.updateProjectionMatrix();scope.dispatchEvent(changeEvent);scope.update();state=STATE.NONE};this.update=function(){var offset=new THREE.Vector3();var quat=new THREE.Quaternion().setFromUnitVectors(object.up,new THREE.Vector3(0,1,0));var quatInverse=quat.clone().inverse();var lastPosition=new THREE.Vector3();var lastQuaternion=new THREE.Quaternion();return function(){var position=scope.object.position;offset.copy(position).sub(scope.target);offset.applyQuaternion(quat);spherical.setFromVector3(offset);if(scope.autoRotate&&state===STATE.NONE){rotateLeft(getAutoRotationAngle())}spherical.theta+=sphericalDelta.theta;spherical.phi+=sphericalDelta.phi;spherical.theta=Math.max(scope.minAzimuthAngle,Math.min(scope.maxAzimuthAngle,spherical.theta));spherical.phi=Math.max(scope.minPolarAngle,Math.min(scope.maxPolarAngle,spherical.phi));spherical.makeSafe();spherical.radius*=scale;spherical.radius=Math.max(scope.minDistance,Math.min(scope.maxDistance,spherical.radius));scope.target.add(panOffset);offset.setFromSpherical(spherical);offset.applyQuaternion(quatInverse);position.copy(scope.target).add(offset);scope.object.lookAt(scope.target);if(scope.enableDamping===true){sphericalDelta.theta*=(1-scope.dampingFactor);sphericalDelta.phi*=(1-scope.dampingFactor)}else{sphericalDelta.set(0,0,0)}scale=1;panOffset.set(0,0,0);if(zoomChanged||lastPosition.distanceToSquared(scope.object.position)>EPS||8*(1-lastQuaternion.dot(scope.object.quaternion))>EPS){scope.dispatchEvent(changeEvent);lastPosition.copy(scope.object.position);lastQuaternion.copy(scope.object.quaternion);zoomChanged=false;return true}return false}}();this.dispose=function(){scope.domElement.removeEventListener('contextmenu',onContextMenu,false);scope.domElement.removeEventListener('mousedown',onMouseDown,false);scope.domElement.removeEventListener('mousewheel',onMouseWheel,false);scope.domElement.removeEventListener('MozMousePixelScroll',onMouseWheel,false);scope.domElement.removeEventListener('touchstart',onTouchStart,false);scope.domElement.removeEventListener('touchend',onTouchEnd,false);scope.domElement.removeEventListener('touchmove',onTouchMove,false);document.removeEventListener('mousemove',onMouseMove,false);document.removeEventListener('mouseup',onMouseUp,false);document.removeEventListener('mouseout',onMouseUp,false);window.removeEventListener('keydown',onKeyDown,false);};var scope=this;var changeEvent={type:'change'};var startEvent={type:'start'};var endEvent={type:'end'};var STATE={NONE: -1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_DOLLY:4,TOUCH_PAN:5};var state=STATE.NONE;var EPS=0.000001;var spherical=new THREE.Spherical();var sphericalDelta=new THREE.Spherical();var scale=1;var panOffset=new THREE.Vector3();var zoomChanged=false;var rotateStart=new THREE.Vector2();var rotateEnd=new THREE.Vector2();var rotateDelta=new THREE.Vector2();var panStart=new THREE.Vector2();var panEnd=new THREE.Vector2();var panDelta=new THREE.Vector2();var dollyStart=new THREE.Vector2();var dollyEnd=new THREE.Vector2();var dollyDelta=new THREE.Vector2();function getAutoRotationAngle(){return 2*Math.PI/60/60*scope.autoRotateSpeed}function getZoomScale(){return Math.pow(0.95,scope.zoomSpeed)}function rotateLeft(angle){sphericalDelta.theta-=angle}function rotateUp(angle){sphericalDelta.phi-=angle}var panLeft=function(){var v=new THREE.Vector3();return function panLeft(distance,objectMatrix){v.setFromMatrixColumn(objectMatrix,0);v.multiplyScalar(-distance);panOffset.add(v)}}();var panUp=function(){var v=new THREE.Vector3();return function panUp(distance,objectMatrix){v.setFromMatrixColumn(objectMatrix,1);v.multiplyScalar(distance);panOffset.add(v)}}();var pan=function(){var offset=new THREE.Vector3();return function(deltaX,deltaY){var element=scope.domElement===document?scope.domElement.body:scope.domElement;if(scope.object instanceof THREE.PerspectiveCamera){var position=scope.object.position;offset.copy(position).sub(scope.target);var targetDistance=offset.length();targetDistance*=Math.tan((scope.object.fov/2)*Math.PI/180.0);panLeft(2*deltaX*targetDistance/element.clientHeight,scope.object.matrix);panUp(2*deltaY*targetDistance/element.clientHeight,scope.object.matrix)}else if(scope.object instanceof THREE.OrthographicCamera){panLeft(deltaX*(scope.object.right-scope.object.left)/scope.object.zoom/element.clientWidth,scope.object.matrix);panUp(deltaY*(scope.object.top-scope.object.bottom)/scope.object.zoom/element.clientHeight,scope.object.matrix)}else{console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');scope.enablePan=false}}}();function dollyIn(dollyScale){if(scope.object instanceof THREE.PerspectiveCamera){scale/=dollyScale}else if(scope.object instanceof THREE.OrthographicCamera){scope.object.zoom=Math.max(scope.minZoom,Math.min(scope.maxZoom,scope.object.zoom*dollyScale));scope.object.updateProjectionMatrix();zoomChanged=true}else{console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');scope.enableZoom=false}}function dollyOut(dollyScale){if(scope.object instanceof THREE.PerspectiveCamera){scale*=dollyScale}else if(scope.object instanceof THREE.OrthographicCamera){scope.object.zoom=Math.max(scope.minZoom,Math.min(scope.maxZoom,scope.object.zoom/dollyScale));scope.object.updateProjectionMatrix();zoomChanged=true}else{console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');scope.enableZoom=false}}function handleMouseDownRotate(event){rotateStart.set(event.clientX,event.clientY)}function handleMouseDownDolly(event){dollyStart.set(event.clientX,event.clientY)}function handleMouseDownPan(event){panStart.set(event.clientX,event.clientY)}function handleMouseMoveRotate(event){rotateEnd.set(event.clientX,event.clientY);rotateDelta.subVectors(rotateEnd,rotateStart);var element=scope.domElement===document?scope.domElement.body:scope.domElement;rotateLeft(2*Math.PI*rotateDelta.x/element.clientWidth*scope.rotateSpeed);rotateUp(2*Math.PI*rotateDelta.y/element.clientHeight*scope.rotateSpeed);rotateStart.copy(rotateEnd);scope.update()}function handleMouseMoveDolly(event){dollyEnd.set(event.clientX,event.clientY);dollyDelta.subVectors(dollyEnd,dollyStart);if(dollyDelta.y>0){dollyIn(getZoomScale())}else if(dollyDelta.y<0){dollyOut(getZoomScale())}dollyStart.copy(dollyEnd);scope.update()}function handleMouseMovePan(event){panEnd.set(event.clientX,event.clientY);panDelta.subVectors(panEnd,panStart);pan(panDelta.x,panDelta.y);panStart.copy(panEnd);scope.update()}function handleMouseUp(event){}function handleMouseWheel(event){var delta=0;if(event.wheelDelta!==undefined){delta=event.wheelDelta}else if(event.detail!==undefined){delta= -event.detail}if(delta>0){dollyOut(getZoomScale())}else if(delta<0){dollyIn(getZoomScale())}scope.update()}function handleKeyDown(event){switch(event.keyCode){case scope.keys.UP:pan(0,scope.keyPanSpeed);scope.update();break;case scope.keys.BOTTOM:pan(0,-scope.keyPanSpeed);scope.update();break;case scope.keys.LEFT:pan(scope.keyPanSpeed,0);scope.update();break;case scope.keys.RIGHT:pan(-scope.keyPanSpeed,0);scope.update();break}}function handleTouchStartRotate(event){rotateStart.set(event.touches[0].pageX,event.touches[0].pageY)}function handleTouchStartDolly(event){var dx=event.touches[0].pageX-event.touches[1].pageX;var dy=event.touches[0].pageY-event.touches[1].pageY;var distance=Math.sqrt(dx*dx+dy*dy);dollyStart.set(0,distance)}function handleTouchStartPan(event){panStart.set(event.touches[0].pageX,event.touches[0].pageY)}function handleTouchMoveRotate(event){rotateEnd.set(event.touches[0].pageX,event.touches[0].pageY);rotateDelta.subVectors(rotateEnd,rotateStart);var element=scope.domElement===document?scope.domElement.body:scope.domElement;rotateLeft(2*Math.PI*rotateDelta.x/element.clientWidth*scope.rotateSpeed);rotateUp(2*Math.PI*rotateDelta.y/element.clientHeight*scope.rotateSpeed);rotateStart.copy(rotateEnd);scope.update()}function handleTouchMoveDolly(event){var dx=event.touches[0].pageX-event.touches[1].pageX;var dy=event.touches[0].pageY-event.touches[1].pageY;var distance=Math.sqrt(dx*dx+dy*dy);dollyEnd.set(0,distance);dollyDelta.subVectors(dollyEnd,dollyStart);if(dollyDelta.y>0){dollyOut(getZoomScale())}else if(dollyDelta.y<0){dollyIn(getZoomScale())}dollyStart.copy(dollyEnd);scope.update()}function handleTouchMovePan(event){panEnd.set(event.touches[0].pageX,event.touches[0].pageY);panDelta.subVectors(panEnd,panStart);pan(panDelta.x,panDelta.y);panStart.copy(panEnd);scope.update()}function handleTouchEnd(event){}function onMouseDown(event){if(scope.enabled===false){return}event.preventDefault();if(event.button===scope.mouseButtons.ORBIT){if(scope.enableRotate===false){return}handleMouseDownRotate(event);state=STATE.ROTATE}else if(event.button===scope.mouseButtons.ZOOM){if(scope.enableZoom===false){return}handleMouseDownDolly(event);state=STATE.DOLLY}else if(event.button===scope.mouseButtons.PAN){if(scope.enablePan===false){return}handleMouseDownPan(event);state=STATE.PAN}if(state!==STATE.NONE){document.addEventListener('mousemove',onMouseMove,false);document.addEventListener('mouseup',onMouseUp,false);document.addEventListener('mouseout',onMouseUp,false);scope.dispatchEvent(startEvent)}}function onMouseMove(event){if(scope.enabled===false){return}event.preventDefault();if(state===STATE.ROTATE){if(scope.enableRotate===false){return}handleMouseMoveRotate(event)}else if(state===STATE.DOLLY){if(scope.enableZoom===false){return}handleMouseMoveDolly(event)}else if(state===STATE.PAN){if(scope.enablePan===false){return}handleMouseMovePan(event)}}function onMouseUp(event){if(scope.enabled===false){return}handleMouseUp(event);document.removeEventListener('mousemove',onMouseMove,false);document.removeEventListener('mouseup',onMouseUp,false);document.removeEventListener('mouseout',onMouseUp,false);scope.dispatchEvent(endEvent);state=STATE.NONE}function onMouseWheel(event){if(scope.enabled===false||scope.enableZoom===false||(state!==STATE.NONE&&state!==STATE.ROTATE)){return}event.preventDefault();event.stopPropagation();handleMouseWheel(event);scope.dispatchEvent(startEvent);scope.dispatchEvent(endEvent)}function onKeyDown(event){if(scope.enabled===false||scope.enableKeys===false||scope.enablePan===false){return}handleKeyDown(event)}function onTouchStart(event){if(scope.enabled===false){return}switch(event.touches.length){case 1:if(scope.enableRotate===false){return}handleTouchStartRotate(event);state=STATE.TOUCH_ROTATE;break;case 2:if(scope.enableZoom===false){return}handleTouchStartDolly(event);state=STATE.TOUCH_DOLLY;break;case 3:if(scope.enablePan===false){return}handleTouchStartPan(event);state=STATE.TOUCH_PAN;break;default:state=STATE.NONE}if(state!==STATE.NONE){scope.dispatchEvent(startEvent)}}function onTouchMove(event){if(scope.enabled===false){return}event.preventDefault();event.stopPropagation();switch(event.touches.length){case 1:if(scope.enableRotate===false){return}if(state!==STATE.TOUCH_ROTATE){return;}handleTouchMoveRotate(event);break;case 2:if(scope.enableZoom===false){return}if(state!==STATE.TOUCH_DOLLY){return;}handleTouchMoveDolly(event);break;case 3:if(scope.enablePan===false){return}if(state!==STATE.TOUCH_PAN){return;}handleTouchMovePan(event);break;default:state=STATE.NONE}}function onTouchEnd(event){if(scope.enabled===false){return}handleTouchEnd(event);scope.dispatchEvent(endEvent);state=STATE.NONE}function onContextMenu(event){event.preventDefault()}scope.domElement.addEventListener('contextmenu',onContextMenu,false);scope.domElement.addEventListener('mousedown',onMouseDown,false);scope.domElement.addEventListener('mousewheel',onMouseWheel,false);scope.domElement.addEventListener('MozMousePixelScroll',onMouseWheel,false);scope.domElement.addEventListener('touchstart',onTouchStart,false);scope.domElement.addEventListener('touchend',onTouchEnd,false);scope.domElement.addEventListener('touchmove',onTouchMove,false);window.addEventListener('keydown',onKeyDown,false);this.update()};THREE.OrbitControls.prototype=Object.create(THREE.EventDispatcher.prototype);THREE.OrbitControls.prototype.constructor=THREE.OrbitControls;Object.defineProperties(THREE.OrbitControls.prototype,{center:{get:function(){console.warn('THREE.OrbitControls: .center has been renamed to .target');return this.target}},noZoom:{get:function(){console.warn('THREE.OrbitControls: .noZoom has been deprecated. Use .enableZoom instead.');return!this.enableZoom},set:function(value){console.warn('THREE.OrbitControls: .noZoom has been deprecated. Use .enableZoom instead.');this.enableZoom=!value}},noRotate:{get:function(){console.warn('THREE.OrbitControls: .noRotate has been deprecated. Use .enableRotate instead.');return!this.enableRotate},set:function(value){console.warn('THREE.OrbitControls: .noRotate has been deprecated. Use .enableRotate instead.');this.enableRotate=!value}},noPan:{get:function(){console.warn('THREE.OrbitControls: .noPan has been deprecated. Use .enablePan instead.');return!this.enablePan},set:function(value){console.warn('THREE.OrbitControls: .noPan has been deprecated. Use .enablePan instead.');this.enablePan=!value}},noKeys:{get:function(){console.warn('THREE.OrbitControls: .noKeys has been deprecated. Use .enableKeys instead.');return!this.enableKeys},set:function(value){console.warn('THREE.OrbitControls: .noKeys has been deprecated. Use .enableKeys instead.');this.enableKeys=!value}},staticMoving:{get:function(){console.warn('THREE.OrbitControls: .staticMoving has been deprecated. Use .enableDamping instead.');return!this.constraint.enableDamping},set:function(value){console.warn('THREE.OrbitControls: .staticMoving has been deprecated. Use .enableDamping instead.');this.constraint.enableDamping=!value}},dynamicDampingFactor:{get:function(){console.warn('THREE.OrbitControls: .dynamicDampingFactor has been renamed. Use .dampingFactor instead.');return this.constraint.dampingFactor},set:function(value){console.warn('THREE.OrbitControls: .dynamicDampingFactor has been renamed. Use .dampingFactor instead.');this.constraint.dampingFactor=value}}});  
  36. </script>  
  37. <script>  
  38. (function(canvasbox, _window){  
  39.         /* 基礎 */  
  40.     var scene, camera, renderer, states, controls;  
  41.     var initCamera; // 初始化照相機  
  42.     // 太陽、水、金、地、火、木、土、土星環、天、天王星環、海王星  
  43.     var taiyang, shui, jin, di, huo, mu, tu, tu_huan, tian, tian_huan, hai;  
  44.     (function(){  
  45.         // 場景  
  46.         scene = new THREE.Scene();  
  47.         // 照相機  
  48.         initCamera = function(){  
  49.             camera = new THREE.PerspectiveCamera(60, canvasbox.clientWidth / canvasbox.clientHeight, 1, 1000);  
  50.         }  
  51.         initCamera();  
  52.         camera.position.set(250, 250, 250);  
  53.         camera.lookAt({  
  54.             x: 0,  
  55.             y: 0,  
  56.             z: 0  
  57.         });  
  58.         // 渲染器  
  59.         renderer = new THREE.WebGLRenderer();  
  60.         renderer.setSize(canvasbox.clientWidth, canvasbox.clientHeight);  
  61.         renderer.clear(0xffffff);  
  62.         canvasbox.appendChild(renderer.domElement);  
  63.         // 監視器  
  64.         states = new Stats();  
  65.         document.body.appendChild(states.domElement);  
  66.         states.domElement.style.position = "absolute";  
  67.         states.domElement.style.left = 0;  
  68.         states.domElement.style.top = 0;  
  69.         //  
  70.         controls = new THREE.OrbitControls(camera);  
  71.     })();  
  72.     /* 光照 */  
  73.     (function(){  
  74.         var huanjing = new THREE.AmbientLight(0x8f8f8f);  
  75.         scene.add(huanjing);  
  76.     })();  
  77.     /* 宇宙背景 */  
  78.     (function(PIC2){  
  79.         var yuzhou_geometr = new THREE.PlaneGeometry(500, 500, 1, 1);  
  80.         var yuzhou_material = new THREE.MeshBasicMaterial({  
  81.             map: THREE.ImageUtils.loadTexture("http://www.w3cfuns.com/attachment/extend/notes/pics/201605/12/212412k1141w4h1nt1fftd.jpg"),  
  82.             side: THREE.DoubleSide  
  83.         });  
  84.         var yuzhou = [];  
  85.         for(var i = 0; i < 6; i++){  
  86.             yuzhou.push(new THREE.Mesh(yuzhou_geometr, yuzhou_material));  
  87.             scene.add(yuzhou[i]);  
  88.         }  
  89.         // 正面  
  90.         yuzhou[0].position.set(0, 0, 250);  
  91.         // 反面  
  92.         yuzhou[1].position.set(0, 0, -250);  
  93.         // 左面  
  94.         yuzhou[2].position.set(-250, 0, 0);  
  95.         yuzhou[2].rotation.set(0, PIC2, 0);  
  96.         // 右面  
  97.         yuzhou[3].position.set(250, 0, 0);  
  98.         yuzhou[3].rotation.set(0, PIC2, 0);  
  99.         // 上面  
  100.         yuzhou[4].position.set(0, 250, 0);  
  101.         yuzhou[4].rotation.set(PIC2, 0, 0);  
  102.         // 下面  
  103.         yuzhou[5].position.set(0, -250, 0);  
  104.         yuzhou[5].rotation.set(PIC2, 0, 0);  
  105.     })(Math.PI / 2);  
  106.     /* 星球 */  
  107.     (function(){  
  108.         // 太陽  
  109.         (function(){  
  110.             var taiyang_geometry = new THREE.SphereGeometry(32, 100, 100);  
  111.             var taiyang_material = new THREE.MeshLambertMaterial({  
  112.                 emissive: 0xe65f05,  
  113.                 map: THREE.ImageUtils.loadTexture("http://www.w3cfuns.com/attachment/extend/notes/pics/201605/12/212414y669k6hq6yq9yoyd.jpg"),  
  114.                 side: THREE.DoubleSide,  
  115.                 color: 0xffffff  
  116.             });  
  117.             taiyang = new THREE.Mesh(taiyang_geometry, taiyang_material);  
  118.             scene.add(taiyang);  
  119.             taiyang.position.set(0, 0, 0);  
  120.             var taiyang_light = new THREE.PointLight(0xffffff, 1, 350);  
  121.             taiyang_light.position.set(0, 0, 0);  
  122.             scene.add(taiyang_light);  
  123.         })();  
  124.         // 水星  
  125.         (function(){  
  126.             var shui_geometry = new THREE.SphereGeometry(1, 100, 100);  
  127.             var shui_material = new THREE.MeshLambertMaterial({  
  128.                 map: THREE.ImageUtils.loadTexture("http://www.w3cfuns.com/attachment/extend/notes/pics/201605/12/212414pff85jucjf2fc5aj.jpg"),  
  129.                 side: THREE.DoubleSide,  
  130.             });  
  131.             shui = new THREE.Mesh(shui_geometry, shui_material);  
  132.             scene.add(shui);  
  133.             shui.position.set(0, 0, 35);  
  134.         })();  
  135.         // 金星  
  136.         (function(){  
  137.             var jin_geometry = new THREE.SphereGeometry(2, 100, 100);  
  138.             var jin_material = new THREE.MeshLambertMaterial({  
  139.                 map: THREE.ImageUtils.loadTexture("http://www.w3cfuns.com/attachment/extend/notes/pics/201605/12/212413v1pqsfp17046np69.jpg"),  
  140.                 side: THREE.DoubleSide,  
  141.             });  
  142.             jin = new THREE.Mesh(jin_geometry, jin_material);  
  143.             scene.add(jin);  
  144.             jin.position.set(0, 0, 42);  
  145.         })();  
  146.         // 地球  
  147.         (function(){  
  148.             var di_geometry = new THREE.SphereGeometry(4, 100, 100);  
  149.             var di_material = new THREE.MeshLambertMaterial({  
  150.                 map: THREE.ImageUtils.loadTexture("http://www.w3cfuns.com/attachment/extend/notes/pics/201605/12/212412na5paf7hzrp710pg.jpg"),  
  151.                 side: THREE.DoubleSide,  
  152.             });  
  153.             di = new THREE.Mesh(di_geometry, di_material);  
  154.             scene.add(di);  
  155.             di.position.set(0, 0, 55);  
  156.         })();  
  157.         // 火星  
  158.         (function(){  
  159.             var huo_geometry = new THREE.SphereGeometry(5, 100, 100);  
  160.             var huo_material = new THREE.MeshLambertMaterial({  
  161.                 map: THREE.ImageUtils.loadTexture("http://www.w3cfuns.com/attachment/extend/notes/pics/201605/12/212412p6qt9qgqzo1t96nd.jpg"),  
  162.                 side: THREE.DoubleSide,  
  163.             });  
  164.             huo = new THREE.Mesh(huo_geometry, huo_material);  
  165.             scene.add(huo);  
  166.             huo.position.set(0, 0, 70);  
  167.         })();  
  168.         // 木星  
  169.         (function(){  
  170.             var mu_geometry = new THREE.SphereGeometry(17, 100, 100);  
  171.             var mu_material = new THREE.MeshLambertMaterial({  
  172.                 map: THREE.ImageUtils.loadTexture("http://www.w3cfuns.com/attachment/extend/notes/pics/201605/12/212413y6svmlc52tv288mp.jpg"),  
  173.                 side: THREE.DoubleSide,  
  174.             });  
  175.             mu = new THREE.Mesh(mu_geometry, mu_material);  
  176.             scene.add(mu);  
  177.             mu.position.set(0, 0, 100);  
  178.             mu.rotation.set(0, 20, 0);  
  179.         })();  
  180.         // 土星  
  181.         (function(){  
  182.             var tu_geometry = new THREE.SphereGeometry(11, 100, 100);  
  183.             var tu_material = new THREE.MeshLambertMaterial({  
  184.                 map: THREE.ImageUtils.loadTexture("http://www.w3cfuns.com/attachment/extend/notes/pics/201605/12/212416s4xwrvkw0ar6wutu.jpg"),  
  185.                 side: THREE.DoubleSide,  
  186.             });  
  187.             tu = new THREE.Mesh(tu_geometry, tu_material);  
  188.             scene.add(tu);  
  189.             tu.position.set(0, 0, 140);  
  190.             tu.rotation.set(0.5, 0, 0);  
  191.             // 土星環  
  192.             var tu_huan_geometry = new THREE.CylinderGeometry(14, 22, 0, 100, 100, true);  
  193.             var tu_huan_material = new THREE.MeshLambertMaterial({  
  194.                 map: THREE.ImageUtils.loadTexture("http://www.w3cfuns.com/attachment/extend/notes/pics/201605/12/212416ikv311fsy7vif3km.jpg"),  
  195.                 side: THREE.DoubleSide,  
  196.             });  
  197.             tu_huan = new THREE.Mesh(tu_huan_geometry, tu_huan_material);  
  198.             scene.add(tu_huan);  
  199.             tu_huan.position.set(0, 0, 140);  
  200.             tu_huan.rotation.set(0.5, 0, 0);  
  201.         })();  
  202.         // 天王星  
  203.         (function(){  
  204.             var tian_geometry = new THREE.SphereGeometry(9, 100, 100);  
  205.             var tian_material = new THREE.MeshLambertMaterial({  
  206.                 map: THREE.ImageUtils.loadTexture("http://www.w3cfuns.com/attachment/extend/notes/pics/201605/12/212414q44z3zeaaenqerbh.jpg"),  
  207.                 side: THREE.DoubleSide,  
  208.             });  
  209.             tian = new THREE.Mesh(tian_geometry, tian_material);  
  210.             scene.add(tian);  
  211.             tian.position.set(0, 0, 170);  
  212.             tian.rotation.set(0, 0, 0.3);  
  213.             // 天王星環  
  214.             var tian_huan_geometry = new THREE.CylinderGeometry(10, 12, 0, 100, 100, true);  
  215.             var tian_huan_material = new THREE.MeshLambertMaterial({  
  216.                 map: THREE.ImageUtils.loadTexture("http://www.w3cfuns.com/attachment/extend/notes/pics/201605/12/212415e2vkzfvkyjijb386.jpg"),  
  217.                 side: THREE.DoubleSide,  
  218.             });  
  219.             tian_huan = new THREE.Mesh(tian_huan_geometry, tian_huan_material);  
  220.             scene.add(tian_huan);  
  221.             tian_huan.position.set(0, 0, 170);  
  222.             tian_huan.rotation.set(0, 0, 0.3);  
  223.         })();  
  224.         // 海王星  
  225.         (function(){  
  226.             var hai_geometry = new THREE.SphereGeometry(6, 100, 100);  
  227.             var hai_material = new THREE.MeshLambertMaterial({  
  228.                 map: THREE.ImageUtils.loadTexture("http://www.w3cfuns.com/attachment/extend/notes/pics/201605/12/212412utl29a6tzaucac6l.jpg"),  
  229.                 side: THREE.DoubleSide,  
  230.             });  
  231.             hai = new THREE.Mesh(hai_geometry, hai_material);  
  232.             scene.add(hai);  
  233.             hai.position.set(0, 0, 192);  
  234.         })();  
  235.     })();  
  236.     /*座標系  
  237.     // 畫線x  
  238.     (function(){  
  239.         var geometry = new THREE.Geometry();  
  240.         var material = new THREE.LineBasicMaterial( { vertexColors: true } );  
  241.         var color = new THREE.Color( 0xffffff );  
  242.         // 線的材質可以由2點的顏色決定  
  243.         var p1 = new THREE.Vector3(200, 0, 0);  
  244.         var p2 = new THREE.Vector3(0, 0, 0);  
  245.         geometry.vertices.push(p1);  
  246.         geometry.vertices.push(p2);  
  247.         geometry.colors.push(color, color);  
  248.         var line = new THREE.Line( geometry, material, THREE.LinePieces );  
  249.         scene.add(line);  
  250.     })();  
  251.     // 畫線y  
  252.     (function(){  
  253.         var geometry = new THREE.Geometry();  
  254.         var material = new THREE.LineBasicMaterial( { vertexColors: true } );  
  255.         var color = new THREE.Color( 0x7cfc00 );  
  256.         // 線的材質可以由2點的顏色決定  
  257.         var p1 = new THREE.Vector3(0, 200, 0);  
  258.         var p2 = new THREE.Vector3(0, 0, 0);  
  259.         geometry.vertices.push(p1);  
  260.         geometry.vertices.push(p2);  
  261.         geometry.colors.push(color, color);  
  262.         var line = new THREE.Line( geometry, material, THREE.LinePieces );  
  263.         scene.add(line);  
  264.     })();  
  265.     // 畫線z  
  266.     (function(){  
  267.         var geometry = new THREE.Geometry();  
  268.         var material = new THREE.LineBasicMaterial( { vertexColors: true } );  
  269.         var color = new THREE.Color( 0x00ffff );  
  270.         // 線的材質可以由2點的顏色決定  
  271.         var p1 = new THREE.Vector3(0, 0, 200);  
  272.         var p2 = new THREE.Vector3(0, 0, 0);  
  273.         geometry.vertices.push(p1);  
  274.         geometry.vertices.push(p2);  
  275.         geometry.colors.push(color, color);  
  276.         var line = new THREE.Line( geometry, material, THREE.LinePieces );  
  277.         scene.add(line);  
  278.     })();  
  279.     */  
  280.     /* 初始化 */  
  281.     (function(){  
  282.         var PI2 = 2 * Math.PI; // 弧度的最大值  
  283.         var zuobiaoxi = [ // 顯示座標系的資訊  
  284.             document.getElementById("zuobiao-x"), // X  
  285.             document.getElementById("zuobiao-y"), // Y  
  286.             document.getElementById("zuobiao-z")  // Z  
  287.         ];  
  288.         // 自轉  
  289.         function zizhuan(){  
  290.             taiyang.rotation.y = taiyang.rotation.y + 0.01 >= 2 * PI2 ? 0 : taiyang.rotation.y + 0.01; // 太陽自轉  
  291.             shui.rotation.y = shui.rotation.y + 0.1 >= 2 * PI2 ? 0 : shui.rotation.y + 0.1;            // 水星自轉  
  292.             jin.rotation.y = jin.rotation.y + 0.05 >= 2 * PI2 ? 0 : jin.rotation.y + 0.05;             // 金星自轉  
  293.             di.rotation.y = di.rotation.y + 0.05 >= 2 * PI2 ? 0 : di.rotation.y + 0.05;                // 地球自轉  
  294.             huo.rotation.y = huo.rotation.y + 0.03 >= 2 * PI2 ? 0 : huo.rotation.y + 0.03;             // 火星自轉  
  295.             mu.rotation.y = mu.rotation.y + 0.003 >= 2 * PI2 ? 0 : mu.rotation.y + 0.003;              // 木星自轉  
  296.             tu.rotation.y = tu.rotation.y + 0.01 >= 2 * PI2 ? 0 : tu.rotation.y + 0.01;                // 土星自轉  
  297.             tian.rotation.y = tian.rotation.y + 0.005 >= 2 * PI2 ? 0 : tian.rotation.y + 0.005;        // 天王自轉  
  298.             hai.rotation.y = hai.rotation.y + 0.003 >= 2 * PI2 ? 0 : hai.rotation.y + 0.003;           // 海王星自轉  
  299.         }  
  300.         // 定義角度  
  301.         var shui_deg, jin_deg, di_deg, huo_deg, mu_deg, tu_deg, tian_deg, hai_deg;  
  302.         shui_deg = jin_deg = di_deg = huo_deg = mu_deg = tu_deg = tian_deg = hai_deg = 0;  
  303.         // 公轉  
  304.         function gongzhuan(){  
  305.             // 水星  
  306.             shui_deg = shui_deg + 0.1 >= PI2 ? 0 : shui_deg + 0.1;  
  307.             shui.position.set(35 * Math.sin(shui_deg), 0, 35 * Math.cos(shui_deg));  
  308.             // 金星  
  309.             jin_deg = jin_deg + 0.07 >= PI2 ? 0 : jin_deg + 0.07;  
  310.             jin.position.set(42 * Math.sin(jin_deg), 0, 42 * Math.cos(jin_deg));  
  311.             // 地球  
  312.             di_deg = di_deg + 0.03 >= PI2 ? 0 : di_deg + 0.03;  
  313.             di.position.set(55 * Math.sin(di_deg), 0, 55 * Math.cos(di_deg));  
  314.             // 火星  
  315.             huo_deg = huo_deg + 0.01 >= PI2 ? 0 : huo_deg + 0.01;  
  316.             huo.position.set(70 * Math.sin(huo_deg), 0, 70 * Math.cos(huo_deg));  
  317.             // 木星  
  318.             mu_deg = mu_deg + 0.002 >= PI2 ? 0 : mu_deg + 0.002;  
  319.             mu.position.set(100 * Math.sin(mu_deg), 0, 100 * Math.cos(mu_deg));  
  320.             // 土星  
  321.             tu_deg = tu_deg + 0.0009 >= PI2 ? 0 : tu_deg + 0.0009;  
  322.             tu.position.set(140 * Math.sin(tu_deg), 0, 140 * Math.cos(tu_deg));  
  323.             tu_huan.position.set(140 * Math.sin(tu_deg), 0, 140 * Math.cos(tu_deg));  
  324.             // 天王星  
  325.             tian_deg = tian_deg + 0.0005 >= PI2 ? 0 : tian_deg + 0.0005;  
  326.             tian.position.set(170 * Math.sin(tian_deg), 0, 170 * Math.cos(tian_deg));  
  327.             tian_huan.position.set(170 * Math.sin(tian_deg), 0, 170 * Math.cos(tian_deg));  
  328.             // 海王星  
  329.             hai_deg = hai_deg + 0.0003 >= PI2 ? 0 : hai_deg + 0.0003;  
  330.             hai.position.set(192 * Math.sin(hai_deg), 0, 192 * Math.cos(hai_deg));  
  331.         }  
  332.         // 顯示資訊  
  333.         function displayXYZ(){  
  334.             zuobiaoxi[0].innerHTML = parseInt(camera.position.x);  // 攝像機X  
  335.             zuobiaoxi[1].innerHTML = parseInt(camera.position.y);  // 攝像機Y  
  336.             zuobiaoxi[2].innerHTML = parseInt(camera.position.z);  // 攝像機Z  
  337.         }  
  338.         // 視窗改變事件  
  339.         function windowChange(){  
  340.             var x = camera.position.x,  
  341.                 y = camera.position.y,  
  342.                 z = camera.position.z;  
  343.             initCamera();  
  344.             controls = new THREE.OrbitControls(camera);  
  345.             camera.position.set(x, y, z);  
  346.             camera.lookAt({  
  347.                 x: 0,  
  348.                 y: 0,  
  349.                 z: 0  
  350.             });  
  351.             renderer.setSize(canvasbox.clientWidth, canvasbox.clientHeight);  
  352.             displayXYZ();  
  353.         }  
  354.         // 動畫  
  355.         function animate(){  
  356.             states.begin();  
  357.             zizhuan();  
  358.             gongzhuan();  
  359.             renderer.clear();  
  360.             renderer.render(scene, camera);  
  361.             states.end();  
  362.             requestAnimationFrame(animate);  
  363.         }  
  364.         // 初始化  
  365.         function init(){  
  366.             displayXYZ();  
  367.             _window.addEventListener("resize", windowChange, false);  
  368.             controls.addEventListener("change", displayXYZ, false);  
  369.             requestAnimationFrame(animate);  
  370.         }  
  371.         init();  
  372.     })();  
  373. })(document.getElementById("canvasbox"), window);  
  374. </script>  
  375. </body>  
  376. </html>  

相關文章