1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| import * as THREE from 'three' import { OrbitControls } from 'three/addons/controls/OrbitControls.js' import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 100 ) camera.position.set(20, 5, 0)
const renderer = new THREE.WebGLRenderer() renderer.setSize(window.innerWidth, window.innerHeight) app.appendChild(renderer.domElement)
const ambLight = new THREE.AmbientLight()
const dirLight = new THREE.DirectionalLight()
dirLight.position.set(5, 5, 5)
scene.add(ambLight, dirLight)
const loader = new GLTFLoader() loader.load('./models/地形.glb', (glb) => { glb.scene.scale.set(3, 3, 3) const mesh = glb.scene.children[0] const pos = mesh.geometry.attributes.position const count = pos.count
const yArr = [] for (let i = 0; i < count; i++) { yArr.push(pos.getY(i)) }
yArr.sort((a, b) => a - b)
const minY = yArr[0] const maxY = yArr[yArr.length - 1] const yHeight = maxY - minY
const colorArr = [] const c1 = new THREE.Color(0x0000ff) const c2 = new THREE.Color(0xff0000)
for (let i = 0; i < count; i++) { const percent = (pos.getY(i) - minY) / yHeight
const c = c1.clone().lerp(c2, percent) colorArr.push(c.r, c.g, c.b) }
const colors = new Float32Array(colorArr)
mesh.geometry.attributes.color = new THREE.BufferAttribute(colors, 3)
mesh.material = new THREE.MeshLambertMaterial({ vertexColors: true, side: THREE.DoubleSide, })
scene.add(glb.scene) })
const controls = new OrbitControls(camera, app)
renderer.setAnimationLoop(() => { renderer.render(scene, camera) })
|