KITASENJU DESIGN BLOG

memo, html, javascript, unity

buffergeometryで矩形をかく

宣言

// BufferGeometryを使って四角形を作成
const geometry = new THREE.BufferGeometry();

// 頂点データを定義
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   // 左上
]);

// 頂点データをBufferAttributeとしてgeometryに追加
geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));

// インデックスを定義(2つの三角形を指定)
const indices = new Uint16Array([
    0, 1, 2, // 最初の三角形
    0, 2, 3  // 2番目の三角形
]);

// インデックスをgeometryに追加
geometry.setIndex(new THREE.BufferAttribute(indices, 1));

// マテリアルを作成
const material = new THREE.MeshBasicMaterial({color: 0xff0000, side: THREE.DoubleSide});

// 四角形のメッシュを作成し、シーンに追加
const rectangle = new THREE.Mesh(geometry, material);
scene.add(rectangle);

動的に変更

function animate() {
    requestAnimationFrame(animate);

    // 頂点データを更新
    const time = performance.now() * 0.001; // 時間を取得(秒)
    const amplitude = 0.5; // 振幅
    const frequency = 1.0; // 周波数

    for (let i = 0; i < vertices.length / 3; i++) {
        // サイン波でY座標を更新
        vertices[i * 3 + 1] = Math.sin(time * frequency + i) * amplitude;
    }

    // 頂点データのBufferAttributeを更新
    geometry.attributes.position.needsUpdate = true;

    // 四角形を回転させる
    rectangle.rotation.x += 0.01;
    rectangle.rotation.y += 0.01;

    // レンダリングを更新
    renderer.render(scene, camera);
}


"FOOTER"