正常情況用threejs 點生成matrix4,方法為:
例如生成饒Y軸旋轉的矩陣
我們要的結果為:
[cos, 0, -sin, 0,
0, 1, 0, 0,
sin, 0, cos, 0,
0, 0, 0, 1]
代碼
getMatrix4FromY(rotateAngle: number): THREE.Matrix4 { let sin = Math.sin(rotateAngle), cos = Math.cos(rotateAngle); let matrix = new THREE.Matrix4(); matrix.set(cos, 0, -sin, 0, 0, 1, 0, 0, sin, 0, cos, 0, 0, 0, 0, 1) return matrix }
最后的結果為:
[cos, 0, sin, 0,
0, 1, 0, 0,
-sin, 0, cos, 0,
0, 0, 0, 1]
原因是我們最開始想要的結果是可以在wegbl里面直接生成matrix的,但是使用THREE.Matrix4.set()之后,
set方法會將數組順序排列方式改變
以下為THREE.Matrix4.set()方法源碼:
set:
function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { var te = this.elements; te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; return this; }
解決方案:
不用先自己算好想要的矩陣結果是什么,直接調用
THREE.Matrix4.makeRotationAxis(axis, angle)方法生成想要的矩陣
eg:生成饒Y軸旋轉的矩陣
let matrix = new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(0, 1, 0), rotateAngle)
注:該方法不適合mesh等繞自身旋轉的obj生成matrix