Threejs实现闪电效果

本文描述了一次尝试用Three.js在WebGL中实现闪电效果的经历,包括基本场景搭建、粒子效果的创建、分叉线的随机生成,以及动画的加入。作者分享了失败的尝试和最终改进思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是一次比较失败的功能实现,本来想网上很少有threejs实现闪电效果的,但是我觉得好像可以做出来,就尝试着做了,结果做出来的太丑了,但是不能时间白费,所以记录下,总得有个交代。

        首先还是搭建出基础的场景

initScene(){
      this.scene = new THREE.Scene();
      const axesHelper = new THREE.AxesHelper( 10);
      axesHelper.position.set(0,0,0)
      this.scene.add( axesHelper );
    },
    initCamera(){
      this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000);
      this.camera.position.set(1000,1000,1000);
      this.camera.lookAt(500,100,500)
    },
initRenderer(){
      this.renderer = new THREE.WebGLRenderer({ antialias: true });
      this.container = document.getElementById("container")
      this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
      this.renderer.setClearColor('#000000', 1.0);
      this.container.appendChild(this.renderer.domElement);
    },
    initControl(){
      this.controls = new OrbitControls(this.camera, this.renderer.domElement);
      this.controls.enableDamping = true;
      this.controls.maxPolarAngle = Math.PI / 2.2;      // // 最大角度
      this.camera.position.set(1000,1000,1000);
      this.camera.lookAt(500,100,500)
    },
    initAnimate() {
    requestAnimationFrame(this.initAnimate);
      this.renderer.render(this.scene, this.camera);
    },

有了基础的场景之后,开始绘制闪电,首先闪电是歪歪扭扭的不是笔直的,所以想着要用到随机数,使用粒子效果做出一个个点,并且是歪歪扭扭往一个方向延伸的,

initLightNing() {
      // Geometry
      const particlesGeometry = new THREE.BufferGeometry()
      const count = 5000
      const positions = new Float32Array(count * 3)
      let beginX = 0;let beginY = 0;let beginZ = 0;
      for(let i = 0; i < count * 3; i = i+3 ){
        positions[i] = beginX + (Math.random())
        positions[i+1] = beginY + (Math.random()*0.8)
        positions[i+2] = beginZ + (Math.random())
        beginX = positions[i];
        beginY = positions[i+1];
        beginZ = positions[i+2];
      }
      particlesGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3))
      // Material
      const particlesMaterial = new THREE.PointsMaterial({
        size: 4,
        sizeAttenuation: true
      })
      particlesMaterial.color = new THREE.Color(0xffffff);
      // Points
      const particles = new THREE.Points(particlesGeometry, particlesMaterial)
      particles.name = 'lightning'
      this.scene.add(particles)
    },

然后就有了这样的效果,一切往我想的方向进行,得到了一条歪歪扭扭的曲线

这样的曲线当做闪电的主分支,然后加点叉就好了ÿ

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

baker_zhuang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值