three BufferAttribute 基本知识

71 阅读1分钟

BufferAttribute 能做什么,是什么

  • BufferAttribute 是一个几体何自定义的API
  • BufferAttribute 通过定义几何体的顶点来生成几何体
  • BufferAttribute 能通过设置索引来优化程序性能

一个基本的使用示例



    const DOMEl = snake.value;
    // 获取 DOMEl 的宽度和高度,以设置渲染器的大小。
    const width = DOMEl.clientWidth;
    const height = DOMEl.clientHeight;

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize( width, height );
    DOMEl.appendChild( renderer.domElement );

    const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 500 );
    camera.position.set( 0, 0, 100 );
    camera.lookAt( 0, 0, 0 );

    const scene = new THREE.Scene();
    // 创建顶点数据(4 个顶点,每个顶点有 3 个分量)
    const vertices = new Float32Array([
    -1.0, -1.0, 0.0,  // 左下角
    1.0, -1.0, 0.0,  // 右下角
    1.0,  1.0, 0.0,  // 右上角
    -1.0,  1.0, 0.0   // 左上角
    ]);

    // 创建顶点索引数据(定义两个三角形组成一个四边形)
    const indices = new Uint16Array([
    0, 1, 2,  // 第一个三角形
    2, 3, 0   // 第二个三角形
    ]);

    // 创建 BufferAttribute 并附加到 BufferGeometry
    const geometry = new THREE.BufferGeometry();
    // itemSize = 3 因为每个顶点都是一个三元组。
    geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));
    // itemSize = 3 因为每个顶点都是一个1元组。
    geometry.setIndex(new THREE.BufferAttribute(indices, 1));

    // 创建材质
    const material = new THREE.MeshBasicMaterial({ color: 0xff0000, side: THREE.DoubleSide });

    // 创建网格并添加到场景中
    const mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);
    
    renderer.render( scene, camera );