2012-01-26 85 views
3

我想要在3D空间中旋转对象,以便前端始终显示鼠标。使用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; 

首先是unprojection正确吗?其次,如何计算角度?它只是棕褐色(mouseX/mouseY)?我试图让更多的三维数学,所以一点点解释会很好。

在此先感谢。

+0

旋转如何?你有3个不同的轴'旋转?你究竟想要鼠标控制旋转? – hypervisor666 2012-05-12 22:21:47

+0

这是将视差效果提升到一个新的水平......让鼠标决定嵌入对象的3D内容如何“看起来”在鼠标指针上。 +1为原创的想法。 – arttronics 2012-06-10 00:36:07

+0

对于**视差伪3D效果**,看看这个[示例](http://stephband.info/jparallax/demos/index.html)。 – arttronics 2012-06-10 08:54:43

回答

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