three.js粒子系统-通过加载纹理贴图实现下雪特效(vue中使用three.js45)

本文介绍在Vue中实现下雪特效的方法。首先阐述纹理导入过程,包括纹理图片存放路径、获取环境变量中的BASE_URL及用THREE.TextureLoader加载纹理贴图。接着说明创建下雪特效,用加载的纹理贴图创建雪花,在render()函数中调用rainAnimation()实现动画,还展示了demo效果与代码。

1.VUE中纹理导入过程

1.1纹理图片存放路径

vue中导入时默认的public下,所以要使用的纹理图片需要放在该路径下,如下图images文件夹下的snow.png就是我们要使用的纹理图片
在这里插入图片描述

1.2获取环境变量中的BASE_URL

在vue的data属性中创建变量publicPath,此变量的值是vue中的环境变量process.env.BASE_URL
在这里插入图片描述

1.3通过THREE.TextureLoader加载纹理贴图

const THIS = this
const textureLoader = new THREE.TextureLoader()
const loadTexture = textureLoader.load(
  `${
     
     THIS.publicPath}images/snow.png`
)

2.创建下雪特效

2.1用加载的纹理贴图创建雪花

示例中将加载的雪花纹理贴图,赋值给THREE.PointsMaterial材质的map属性,获得雪花形状的粒子材质,然后随机创建雪花并添加到Geometry对象的vertices属性中,最后使用THREE.Points创建粒子系统,并把该粒子系统添加到场景

// 创建粒子
createParticleSystem () {
   
   
  const THIS = this
  const textureLoader = new THREE.TextureLoader()
  const loadTexture = textureLoader.load(
    `${
     
     THIS.publicPath}images/snow.png`
  )
  // 创建几何体
  const geom = new THREE.Geometry()
  const material = new THREE.PointsMaterial({
   
   
    map: loadTexture,
    size: this.properties.size.value,
    transparent: this.properties.transparent,
    opacity: this.properties.opacity.value,
    sizeAttenuation: this.properties.sizeAttenuation,
    color: this.properties.color,
    blending: THREE.AdditiveBlending,
    depthTest: false // 解决透明度问题
  })
  const range = 160
  for (let i = 0; i < 3000; i++) {
   
   
    const particle = new THREE.Vector3(
      Math.random() * range - range / 2,
      Math.random() * range * 1.5,
      Math.random() * range - range / 2
    )
    particle.velocityY = 0.1 + Math.random() / 5
    particle.velocityX = (Math.random() - 0.5) / 3
    // 给几何体添加顶点坐标
    geom.vertices.push(particle)
  }
  // 创建粒子系统对象
  this.points = new THREE.Points(geom, material)
  this.points.sortParticles = true
  this.points.verticesNeedUpdate = true
  // 将粒子系统对象添加到场景
  this.scene.add(this.points)
}

2.2 实现下雪特效动画

在render() 函数中调用下面rainAnimation() 函数实现下雪特效动画

rainAnimation () {
   
   
  const vertices = this.points.geometry.vertices
  vertices.forEach(v => {
   
   
    v.y = v.y - v.velocityY * 3
    v.x = v.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值