2012-01-26 100 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);