使用Three.js将3D对象旋转到鼠标

时间:2012-01-26 23:48:06

标签: math mouse rotation three.js

我想在3D空间中旋转对象,以便正面总是看向鼠标。

function onMouseMove(event){
             mouse3D = projector.unprojectVector(
                 new THREE.Vector3( event.clientX, event.clientY, 0.5 ), camera );
}

var angle = ??;
box.rotation.y = angle;

首先是非投影是否正确?其次如何计算角度?它只是棕褐色(mouseX / mouseY)?我正在努力学习3D数学,所以稍微解释一下就好了。

提前致谢。

1 个答案:

答案 0 :(得分:3)

// Direction we are already facing (without rotation)
var forward = new Vector3(0,0,-1);

// Direction we want to be facing (towards mouse pointer)
var target = new Vector3().sub(mouse3D, box.position).normalize();

// Axis and angle of rotation
var axis = new Vector3().cross(forward, target);
var sinAngle = axis.length(); // |u x v| = |u|*|v|*sin(a)
var cosAngle = forward.dot(target); // u . v = |u|*|v|*cos(a)
var angle = Math.atan2(sinAngle, cosAngle); // atan2(sin(a),cos(a)) = a
axis.normalize();

// Overwrite rotation
box.rotation.makeRotationAxis(axis, angle);

或者,您可以使用四元数:

// Overwrite rotation
box.useQuaternion = true;
box.quaternion.setFromAxisAngle(axis, angle);