3D星空

100 阅读2分钟

接上文 球体

今天搞星空

技术栈依然和之前一样parcel+html+three;

今天我们来学下另一个创建几何体的实例BufferGeometry;

const particlesGeometry = new THREE.BufferGeometry();
const count = 5000;//设置星空的数量,尽量设置的多一些
  • 当然我们都知道每个顶点的位置都由3个浮点数组成(x, y, z);
  • 每个顶点的颜色通常由 3 个浮点数组成(R, G, B),分别表示红色、绿色和蓝色的分量。
// 设置缓冲区数组
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 pointsMaterial = new THREE.PointsMaterial();
pointsMaterial.size = 0.5;
pointsMaterial.color.set(0xfff000);
// 相机深度而衰减
pointsMaterial.sizeAttenuation = true;

注意:当sizeAttenuation设置为 true 时,点的大小会根据摄像机的距离动态调整。具体来说:

  • 当点靠近摄像机时,点的大小会减小。
  • 当点远离摄像机时,点的大小会增大。

这种动态调整的目的是让点在视图中保持相对一致的视觉大小,从而避免因透视效果导致的点大小变化过于剧烈。

设置纹理


// 载入纹理
const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load("./zs2.png");

设置材质相关属性让顶点看起来更合理

// 设置点材质纹理
pointsMaterial.map = texture;//作用是为点材质设置纹理贴图
pointsMaterial.alphaMap = texture;//作用是为点材质设置透明度纹理(Alpha Map)
pointsMaterial.transparent = true;//作用是启用材质的透明度
pointsMaterial.depthWrite = false;//作用是禁用材质的深度写入
pointsMaterial.blending = THREE.AdditiveBlending;//作用是设置材质的混合模式为加性混合(Additive Blending)它将点的颜色与背景颜色相加,从而产生发光效果
// 设置启动顶点颜色
pointsMaterial.vertexColors = true;`vertexColors` 属性设置为 `true` 时,材质会使用几何体的顶点颜色,而不是使用统一的材质颜色0xfff000

最后将该点云系统渲染出来

const points = new THREE.Points(particlesGeometry, pointsMaterial);

下面来看渲染出来的效果

chrome-capture-2025-1-6.gif