threejs 实现漫天飞舞的雪花

threejs yekong 430℃

今天我们通过threejs来实现下雪的效果。上一节我们学习了threejs 应用顶点着色打造绚丽多彩的星空,所以我们在上一节的基础上来实现下雪的效果。

threejs 实现漫天飞舞的雪花

首先准备素材

我们可以在iconfont平台上来找一个雪花的图标。
字体图标

代码封装

我们将上一节星空的生成封装起来,用来创建雪花下落的效果。

function createPoints(size = 0.5) {

    const particlesGeometry = new THREE.BufferGeometry()
    const count = 5000
    
    // 设置缓冲区数组
    const positions = new Float32Array(count * 3);
    
    
    // 设置粒子顶点颜色
    const colors = new Float32Array(count * 3)
    // 设置顶点
    
    for (let i = 0; i < count * 3; i++) {
      positions[i] = (Math.random() - 0.5) * 100;
      colors[i] = Math.random()
    }
    
    particlesGeometry.setAttribute('position',
        new THREE.BufferAttribute(positions, 3)
    )
    particlesGeometry.setAttribute('color',
        new THREE.BufferAttribute(colors, 3)
    )
    // 设置点材质
    const pointMaterial = new THREE.PointsMaterial()
    
    // 载入纹理
    const textureLoader = new THREE.TextureLoader()
    const texture = textureLoader.load(star)
    pointMaterial.map = texture
    pointMaterial.size = size
    pointMaterial.alphaMap = texture;
    pointMaterial.transparent = true;
    pointMaterial.color.set(0xffffff)
    pointMaterial.depthWrite = true
    pointMaterial.blending = THREE.AdditiveBlending
    // 设置启动顶点颜色
    pointMaterial.vertexColors = true
    
    // 相机衰减
    pointMaterial.sizeAttenuation = true
    const points = new THREE.Points(particlesGeometry, pointMaterial)
    scene.add(points)
    return points
}

创建雪花

我们创建三组雪花

const points1 = createPoints(0.5)
const points2 = createPoints(0.8)
const points3 = createPoints(1)

设置下落的过程

通过控制雪花的rotation.x的位置来实现雪花下落的过程,通过控制y的位置来模拟雪花被风吹动的效果。这里我们通过THREE.Clock方法来设置雪花下落的时间间隔.

const clock = new THREE.Clock();

function render() {
let time = clock.getElapsedTime()
points1.rotation.x = time * 0.3
points2.rotation.x = time * 0.5
points2.rotation.y = time * 0.4
points3.rotation.x = time * 0.2
points3.rotation.y = time * 0.2
renderer.render(scene, camera); //执行渲染操作
requestAnimationFrame(render); //请求再次执行渲染函数render,渲染下一帧
}

屏蔽上升雪花

这样雪花下落的效果就基本完成了,但是在视频中,后面的雪花有一个向上移动的情况,所以我们需要处理一下,通过控制相机的可以范围来屏蔽掉上升的雪花

透视相机的范围调整一下从1000调整为40

// 创建透视相机
const camera = new THREE.PerspectiveCamera(
  75,
  this.width / this.height,
  0.1,
  1000
);
const camera = new THREE.PerspectiveCamera(
  75,
  this.width / this.height,
  0.1,
  40
);

这样我们看到的雪花就只有下降的了。

绚丽多彩的星空演示地址

threejs 实现漫天飞舞的雪花

绚丽多彩的星空实例代码下载

代码开发环境基于vue3 vite js nodejs 14

请确保有一定的代码基础

相关文件下载地址
此资源需支付 ¥1 后下载
支付宝购买扫右侧红包码购买更优惠,如无法下载请联系微信:17331886870
喜欢 (0)
threejs 实现漫天飞舞的雪花