前回のサンプルの内容をこれから少しずつ説明していきます。
http://jsdo.it/yaju3D/pixD
AS3.0 で 3D プログラミングを1から勉強する (2) - 行列の導入
AS3.0 で 3D プログラミングを1から勉強する (3) - 透視投影
このプログラムでは、大きな立方体1個の周りを4個の計5個を表示しています。
Cubeクラスの引数は4つ(x, y, z, len)です。
this.cubes.push(new Cube(0, 0, 0, 50)); this.cubes.push(new Cube(0, 100, 0, 20)); this.cubes.push(new Cube(0, -100, 0, 20)); this.cubes.push(new Cube(100, 0, 0, 20)); this.cubes.push(new Cube(-100, 0, 0, 20)); function Cube(x, y, z, len) { this.points = []; this.points.length = 0; // 立方体の頂点8つを作成する for(var i = 0; i < 8; i++) { var p = new Point3D(x + this.diff(i % 4 % 3 == 0, len), y + this.diff(i % 4 < 2, len), z + this.diff(i < 4, len)); this.points.push(p); } } Cube.prototype.diff = function (f, len) { return f ? len / 2 : -len / 2; };
立方体を構成するには頂点(A-H)の8つ必要ですが、このプログラムではdiff関数を使って何やら妙な計算をしていますね。
x + this.diff(i % 4 % 3 == 0, len) y + this.diff(i % 4 < 2, len) z + this.diff(i < 4, len)
一番大きな立方体の長さ50をトレースした値は下記となります。
立方体の中心(0,0,0)を基準にした頂点座標で、横方向をX軸、縦方向をY軸、奥行きをZ軸とします。
図に合わせた頂点も記述してみました。
//i x y z //0 25 25 25 頂点A ( x, y, z) //1 -25 25 25 頂点B (-x, y, z) //2 -25 -25 25 頂点C (-x -y, z) //3 25 -25 25 頂点D ( x,-y, z) //4 25 25 -25 頂点E ( x, y,-z) //5 -25 25 -25 頂点F (-x, y,-z) //6 -25 -25 -25 頂点G (-x,-y,-z) //7 25 -25 -25 頂点H ( x,-y,-z)
正方の立方体を作成するには、diff関数を使った方法もお手軽でいいかも知れません。
※頂点A-Zの順番は、スクリーン座標を基にした順番でありOpenGLやDirectXといった3Dライブラリのデカルト座標にした場合には違ってきます。
右手? 左手? 座標系の話
http://wgld.org/d/webgl/w003.html