LoginSignup
25
22

More than 5 years have passed since last update.

[WebGL] Three.jsのBufferGeometryでオブジェクトを作る

Last updated at Posted at 2015-06-11

BufferGeometryBufferAttributeを使うことで、比較的低レベルなAPIを意識した記述が可能となります。

以下は、BufferGeometryを使ってプレーンを描くサンプルコードです。
Three.jsが用意してくれているマテリアルをそのまま使うことができたりするので、ある程度低レベルで操作しながらもThree.jsの恩恵を受けられるのが大きいでしょう。

動作アニメ

サンプルコード

// BufferGeometryを生成
var geometry = new THREE.BufferGeometry();

// 平面用の頂点を定義
// d - c
// |   |
// a - b
var vertexPositions = [
    [-1.0, -1.0, 1.0], // a
    [ 1.0, -1.0, 1.0], // b
    [ 1.0,  1.0, 1.0], // c
    [-1.0,  1.0, 1.0]  // d
];

// Typed Arrayで頂点データを保持
var vertices = new Float32Array(vertexPositions.length * 3);
for (var i = 0; i < vertexPositions.length; i++) {
    vertices[i * 3 + 0] = vertexPositions[i][0];
    vertices[i * 3 + 1] = vertexPositions[i][1];
    vertices[i * 3 + 2] = vertexPositions[i][2];
}

// 頂点インデックスを生成
var indices = new Uint16Array([
    0, 1, 2,
    2, 3, 0
]);

// attributesを追加
geometry.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
geometry.addAttribute('index',    new THREE.BufferAttribute(indices,  1));

var material = new THREE.MeshLambertMaterial({
    color: 0xff0000
});
var mesh = new THREE.Mesh(geometry, material);
mesh.position.z = -10;

scene.add(mesh);

生のWebGLに似た感じで書きつつ、だいぶコード量が減ってるのが分かると思います。

25
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
22