正常情况用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