且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将对象的旋转定向到 THREE.JS 中的样条点切线

更新时间:2023-10-28 23:07:40

根据经验,***不要直接弄乱object.matrix,而只是设置对象positionrotationscale.让库处理矩阵操作.你需要有 matrixAutoUpdate = true;.

As a rule of thumb, it is best not to mess with the object.matrix directly, and instead just set the object position, rotation, and scale. Let the library handle the matrix manipulations. You need to have matrixAutoUpdate = true;.

要处理旋转部分,首先要得到曲线的切线.

To handle the rotation part, first get the tangent to the curve.

tangent = spline.getTangent( t ).normalize();

您想要旋转对象,使其向上向量(局部 y 向量)指向曲线切向量的方向.首先计算要绕其旋转的轴.轴是垂直于由向上矢量和切线矢量定义的平面的矢量.你使用叉积来得到这个向量.

You want to rotate the object so that it's up-vector (local y-vector) points in the direction of the curve tangent vector. First calculate the axis to rotate around. The axis is a vector perpendicular to the plane defined by the up-vector and the tangent vector. You use the cross-product to get this vector.

axis.crossVectors( up, tangent ).normalize();

请注意,在您的情况下,由于样条曲线位于垂直于 z 轴的平面中,因此刚刚计算的轴将平行于 z 轴.但是,它可能指向正 z 轴或负 z 轴的方向——这取决于切向量的方向.

Note, in your case, since the spline lies in a plane perpendicular to the z-axis, the axis just computed will be parallel to the z-axis. However, it may point in the direction of the positive z-axis or the negative z-axis -- it depends on the direction of the tangent vector.

现在计算向上向量和切线向量之间的角度(以弧度表示).上向量和切向量的点积给出了它们之间夹角的余弦(因为两个向量都是单位长度).然后你必须取反余弦来获得角度本身.

Now calculate the angle in radians between the up vector and the tangent vector. The dot-product of the up vector and the tangent vector give the cosine of the angle between them (since both vectors are of unit length). You then have to take the arc-cosine to get the angle itself.

radians = Math.acos( up.dot( tangent ) );

现在,从轴和角度中提取四元数.

Now, extract the quaternion from the axis and angle.

marker.quaternion.setFromAxisAngle( axis, radians );

[删除过时的小提琴]

three.js r.69

three.js r.69