three.js 實現3D雨落場景--yyn日記

本文主要介紹使用three.js 實現3D雨落場景
廢話不多說,先上圖 (去看效果)

場景圖.png

沒做gif,全是靜態的,直接上代碼,然后解釋一下 幾個關鍵點就行

import * as THREE from 'three'
import { OrbitControls } from '../../../node_modules/three/examples/jsm/controls/OrbitControls'
export default class demo {
  constructor(options) {
    this.scene = null
    this.camera = null
    this.renderer = null
    this.w = null
    this.h = null
    this.fov = 60
    this.near = 1
    this.far = 5000
    this.options = options || {}
    // 立方體
    this.cube = null
    this.controls = null
    this.cylinder = null
    this.sphere = null
    this.sphereArray = []
    this.group = []
  }
  createScene() {
    this.w = window.innerWidth
    this.h = window.innerHeight
    this.scene = new THREE.Scene()
    // this.scene.background = new THREE.Color(0xcccccc)
    // this.scene.fog = new THREE.FogExp2(0xcccccc, 0.002)
    this.camera = new THREE.PerspectiveCamera(
      this.fov,
      this.w / this.h,
      this.near,
      this.far
    )
    this.renderer = new THREE.WebGLRenderer({
      alpha: true,
      antialias: true
    })
    this.renderer.setSize(this.w, this.h)
    this.camera.position.set(400, -50, 0)
    this.camera.lookAt(this.scene.position)
    document
      .querySelector(this.options.el)
      .appendChild(this.renderer.domElement)
    this.createControls()
    this.createLight()
  }
  createBackground() {
    let urls = [`px.jpg`, `nx.jpg`, `py.jpg`, `ny.jpg`, `pz.jpg`, `nz.jpg`]
    let reflectionCube = new THREE.CubeTextureLoader()
      .setPath('/images/app/')
      .load(urls)
    this.scene.background = reflectionCube
    this.renderer.render(this.scene, this.camera)
  }
  // light
  createLight() {
    var light = new THREE.PointLight(0xffffff)
    light.position.set(400, -50, 0)
    this.scene.add(light)
    var light1 = new THREE.DirectionalLight(0x888888)
    this.scene.add(light1)
    var light2 = new THREE.AmbientLight(0xffffff)
    this.scene.add(light2)
  }
  // 創建 小圓球
  createSphere() {
    let geometry = new THREE.SphereBufferGeometry(8, 8, 8)
    let metarial = new THREE.MeshBasicMaterial({
      envMap: this.scene.background
    })
    this.group = new THREE.Group()

    for (let i = 0; i < 10000; i++) {
      this.sphere = new THREE.Mesh(geometry, metarial)
      this.sphere.position.x = Math.random() * 10000 - 5000
      this.sphere.position.y = Math.random() * 10000 - 5000
      this.sphere.position.z = Math.random() * 10000 - 5000
      this.sphere.scale.x = this.sphere.scale.y = this.sphere.scale.z =
        Math.random() * 3 + 1
      this.sphereArray.push(this.sphere)
      this.sphere.updateMatrix()
      // this.sphere.matrixAutoUpdate = false
      this.group.add(this.sphere)
    }
    this.scene.add(this.group)
  }
  // 創建控制器
  createControls() {
    this.controls = new OrbitControls(this.camera, this.renderer.domElement)
    // this.controls.target.set(0, 0, 0) // 設置控制器的焦點,使控制器圍繞這個焦點進行旋轉
    this.controls.enableDamping = true // an animation loop is required when either damping or auto-rotation are enabled
    this.controls.dampingFactor = 0.25
    this.controls.screenSpacePanning = true
    this.controls.enableZoom = false
    this.controls.enablePan = false
    this.controls.minDistance = 10 // 設置移動的最短距離(默認為零)
    this.controls.maxDistance = 400 // 設置移動的最長距離(默認為無窮)
    this.controls.minPolarAngle = Math.PI / 4
    this.controls.maxPolarAngle = Math.PI / 1.5
    // this.controls.update() // 照相機轉動時,必須更新該控制器
  }
  animate() {
    this.sphereArray.forEach(item => {
      item.position.y -= 10
      if (item.position.y < -3000) {
        item.position.y = Math.random() * 10000 - 5000
      }
    })
    requestAnimationFrame(this.animate.bind(this))
    this.controls.update()
    this.render()
  }
  render() {
    this.camera.updateProjectionMatrix()
    this.renderer.render(this.scene, this.camera)
  }
  async init() {
    await this.createScene()
    await this.createBackground()
    await this.createSphere()
    // await this.createCylinder()
    // await this.createCube()
    await this.animate()
  }
}

app.vue頁面 引入 并使用

import demo from './plugins/app/index.js'
let three = new demo({
  el: '#app'
})
export default {
  name: 'app',
  mounted() {
    three.init()
  }
}

下面就解釋一下完成雨落的必要API

createBackground() {
    let urls = [`px.jpg`, `nx.jpg`, `py.jpg`, `ny.jpg`, `pz.jpg`, `nz.jpg`]
    let reflectionCube = new THREE.CubeTextureLoader()
      .setPath('/images/app/')
      .load(urls)
    this.scene.background = reflectionCube
    this.renderer.render(this.scene, this.camera)
  }

首先創建一個場景,添加一個背景貼圖,使用的是CubeTextureLoader

createLight() {
    var light = new THREE.PointLight(0xffffff)
    light.position.set(400, -50, 0)
    this.scene.add(light)
    var light1 = new THREE.DirectionalLight(0x888888)
    this.scene.add(light1)
    var light2 = new THREE.AmbientLight(0xffffff)
    this.scene.add(light2)
  }

其次創建燈光效果,建議初學者挨著挨著試,總會有感覺的,我就是這么過來的,不知道是不是蠢

createSphere() {
    let geometry = new THREE.SphereBufferGeometry(8, 8, 8)
    let metarial = new THREE.MeshBasicMaterial({
      envMap: this.scene.background
    })
    this.group = new THREE.Group()

    for (let i = 0; i < 10000; i++) {
      this.sphere = new THREE.Mesh(geometry, metarial)
      this.sphere.position.x = Math.random() * 10000 - 5000
      this.sphere.position.y = Math.random() * 10000 - 5000
      this.sphere.position.z = Math.random() * 10000 - 5000
      this.sphere.scale.x = this.sphere.scale.y = this.sphere.scale.z =
        Math.random() * 3 + 1
      this.sphereArray.push(this.sphere)
      this.sphere.updateMatrix()
      // this.sphere.matrixAutoUpdate = false
      this.group.add(this.sphere)
    }
    this.scene.add(this.group)
  }

接著是創建10000個小圓球模擬雨滴,使用到的api SphereBufferGeometry MeshBasicMaterial Group Mesh
為什么要使用group API呢? 因為你創建10000個小圓球,你會去做下落,總會落出可視區域,所以你可以采用移除對象再添加對象,直接操作group 不用去挨個挨個移除,但是體驗不好。后面會講到。

 createControls() {
    this.controls = new OrbitControls(this.camera, this.renderer.domElement)
    // this.controls.target.set(0, 0, 0) // 設置控制器的焦點,使控制器圍繞這個焦點進行旋轉
    this.controls.enableDamping = true // an animation loop is required when either damping or auto-rotation are enabled
    this.controls.dampingFactor = 0.25
    this.controls.screenSpacePanning = true
    this.controls.enableZoom = false
    this.controls.enablePan = false
    this.controls.minDistance = 10 // 設置移動的最短距離(默認為零)
    this.controls.maxDistance = 400 // 設置移動的最長距離(默認為無窮)
    this.controls.minPolarAngle = Math.PI / 4
    this.controls.maxPolarAngle = Math.PI / 1.5
    // this.controls.update() // 照相機轉動時,必須更新該控制器
  }

然后創建一個控制器,這個很帥氣。需要用到OrbitControls對象,所以需要引入OrbitControls這個js文件,具體的API去看官網嘛

animate() {
    this.sphereArray.forEach(item => {
      item.position.y -= 10
      if (item.position.y < -3000) {
        item.position.y = Math.random() * 10000 - 5000
      }
    })
    requestAnimationFrame(this.animate.bind(this))
    this.controls.update()
    this.render()
  }

最后,你得循環渲染,所以肯定會用到requestAnimationFrame,這串代碼主要的點是 當然是雨落效果了

this.sphereArray.forEach(item => {
      item.position.y -= 10
      if (item.position.y < -3000) {
        item.position.y = Math.random() * 10000 - 5000
      }
 })

通過遍歷對象數組,給每個元素Y軸設定 10 的偏移量 ,當元素到達一定界值得時候 將他的偏移量重新賦值,那么在循環執行animate方法,就可以達到非常完美的效果了。

查看演示
yyn博客

參考文章:three.js 官網 three.js 中文文檔

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容