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 中文文档

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,366评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,521评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,689评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,925评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,942评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,727评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,447评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,349评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,820评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,990评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,127评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,812评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,471评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,017评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,142评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,388评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,066评论 2 355

推荐阅读更多精彩内容