Orient object's rotation to a spline point tangent in THREE.JS

ぃ、小莉子 提交于 2019-11-27 19:56:05

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();

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();

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 );

EDIT: updated fiddle: http://jsfiddle.net/SCXNQ/891/ for three.js r.69

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!