代码中,引用的材质:
// @ts-ignore
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import gsap from 'gsap' // 导入动画库
import * as dat from 'dat.gui' // 导入dat.gui
// -------------------------------------------------------------------------------------
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.set(0, 0, 10)
const renderer = new THREE.WebGLRenderer({
antialias: true
})
renderer.shadowMap.enabled = true
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.physicallyCorrectLights = true `启用物理光照,更真实`
document.body.appendChild(renderer.domElement)
const axesHelper = new THREE.AxesHelper(5)
scene.add(axesHelper)
const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true
controls.dampingFactor = 0.01
// controls.autoRotate = true // 自动旋转
// controls.autoRotateSpeed = 6 // 自动旋转的速度
const render = () => {
controls.update()
requestAnimationFrame(render) // 在屏幕渲染下一帧画面时,触发回调函数,来执行画面的渲染
renderer.render(scene, camera)
}
render()
// -------------------------------------------------------------------------------------
const particlesGeometry = new THREE.BufferGeometry()
`粒子的数量`
const count = 5000
`粒子的位置`
const position_s = new Float32Array(count * 3)
`设置,粒子顶点颜色
Three.js中,通常使用:RGBA(红、绿、蓝、透明度),四个值来表示颜色,每个值的范围是:0 ~ 1,
这里只分配了(count * 3)个元素,表示,每个粒子只使用RGB颜色(忽略透明度),
但是,更推荐使用:Float32Array(count * 4) 来存储RGBA颜色。`
const colors = new Float32Array(count * 3)
for (let i = 0; i < count * 3; i++) {
// (Math.random() - 0.5) * 100,生成的是 -50 ~ 50 之间的数
position_s[i] = (Math.random() - 0.5) * 100
// 0 ~ 1 的随机值
colors[i] = Math.random()
}
// console.log('position_s=', position_s)
// console.log('colors=', colors)
particlesGeometry.setAttribute('position', new THREE.BufferAttribute(position_s, 3))
`这里的color属性,必须和pointsMaterial.vertexColors属性同时设置,点才会有颜色`
particlesGeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3))
// -------------------------------------------------------------------------------------
// 设置点材质
const pointsMaterial = new THREE.PointsMaterial()
pointsMaterial.size = 0.5
pointsMaterial.color.set(0xfff000)
// 点的大小,根据,它们与相机的距离而自动调整,远离相机时点会变小,靠近相机时点会变大
pointsMaterial.sizeAttenuation = true
const textureLoader = new THREE.TextureLoader()
const texture = textureLoader.load('../public/assets/texture/particles/zs2.png')
pointsMaterial.map = texture
pointsMaterial.alphaMap = texture // 透明度贴图
pointsMaterial.transparent = true // 透明
/*
为false时,该材质不写入深度缓冲区
即:在渲染时,不会影响其他物体的深度值
即:不会影响,场景中其他物体的遮挡关系 */
pointsMaterial.depthWrite = false
/*
材质的混合,值为:THREE.AdditiveBlending(加法混合模式)
即:
在加法混合模式下,渲染的颜色值不是简单地覆盖,而是被相加在一起,
用于创建:【发光效果】、【光线效果】,
能够让【点】或【粒子】看起来像是在【发光】或【产生光线效果】,
在一些特效和场景中非常有用,例如:创建,星空效果、火焰效果等 */
pointsMaterial.blending = THREE.AdditiveBlending
`设置启动顶点颜色`
pointsMaterial.vertexColors = true
const points = new THREE.Points(particlesGeometry, pointsMaterial)
scene.add(points)