月球绕地球的示例

  • Post author:
  • Post category:其他




月球绕地球的示例


import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import {CSS2DRenderer,CSS2DObject} from 'three/examples/jsm/renderers/CSS2DRenderer';

import * as dat from 'dat.gui';
const gui = new dat.GUI();
let moon,earth;
let clock = new THREE.Clock();
const textureLoader = new THREE.TextureLoader();
const scene = new THREE.Scene();


const camera = new THREE.PerspectiveCamera(45, innerWidth, innerHeight, 0.1, 2000);
camera.position.set(10, 5, 20);
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();

scene.add(camera);

const light = new THREE.SpotLight(0xffffff);
light.position.set(0,0,10);
light.castShadow = true;
light.intensity = 2;
scene.add(light);

const light_1 = new THREE.AmbientLight(0xffffff);
light_1.intensity = 0.1;
scene.add(light_1);

const moonGeometry = new THREE.SphereGeometry(0.27,16,16);
const moonMaterial = new THREE.MeshPhongMaterial({
    map:textureLoader.load('./image/img-1.jpg')
});
moon = new THREE.Mesh(moonGeometry,moonMaterial);
moon.receiveShadow = true;
moon.castShadow = true;
scene.add(moon);

const earthGeometry = new THREE.SphereGeometry(2.5,32,32);
const earthMaterial = new THREE.MeshPhongMaterial({
    map:textureLoader.load('./image/test.jpg'),
    shininess:5
    // specularMap
})
earth = new THREE.Mesh(earthGeometry,earthMaterial);
earth.receiveShadow = true;
earth.castShadow = true;
scene.add(earth);

const renderer = new THREE.WebGL1Renderer({
    antialias: true
});

renderer.outputEncoding = THREE.sRGBEncoding;
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;

document.body.appendChild(renderer.domElement);
// scene.add(new THREE.AxesHelper(200))
render();
let oldTime = 0;
function render(){
    let time = clock.getElapsedTime();
    moon.position.set(Math.sin(time) * 5,0,Math.cos(time)*5);
    let axis = new THREE.Vector3(0,1,0);
    // console.log(time - oldTime)
    earth?.rotateOnAxis(axis,(Number.isNaN(time - oldTime)?0:(time - oldTime)) * Math.PI/10)
    renderer.render(scene,camera);
    oldTime = time;
    requestAnimationFrame(render);
}
new OrbitControls(camera,renderer.domElement);
window.onresize = () => {
    camera.aspect = innerWidth / innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(innerWidth, innerHeight);
}










版权声明:本文为qq_38389828原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。