ThreeJS:在平面附近的canera上从屏幕2D坐标转换为世界3D坐标? R73

时间:2016-01-07 16:17:38

标签: three.js

我在坐标转换方面遇到了一些麻烦。 我在屏幕上有一个具有已知坐标(x,y)的物体,我想将它转换为世界坐标(x,y,z),因为它将被投射到相机的近平面上。

到目前为止,我可以像这样在Z平面上进行投影:

var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
vector.unproject( camera );

但不幸的是我无法继续下去:(

2 个答案:

答案 0 :(得分:9)

如果对z分量使用-1,则会投射到近平面,而不是远平面:

www.3rdpartysite.com

假设mouse.x和mouse.y介于-1和1之间。

three.js r.73

答案 1 :(得分:3)

我找到了另一个答案,不知道它是否适合你。



var getSceneToWorld = function(dx, dy) {
var projector = new THREE.Projector();
var mouse3D = new THREE.Vector3(dx / window.innerWidth * 2 - 1, -dy / window.innerHeight * 2 + 1, 0.5);
projector.unprojectVector(mouse3D, camera);
mouse3D.sub(camera.position);
mouse3D.normalize(); 
var rayCaster = new THREE.Raycaster(camera.position, mouse3D); var scale = window.innerWidth * 2; 
var rayDir = new THREE.Vector3(rayCaster.ray.direction.x * scale, rayCaster.ray.direction.y * scale, rayCaster.ray.direction.z * scale);
var rayVector = new THREE.Vector3(camera.position.x + rayDir.x, camera.position.y + rayDir.y, camera.position.z + rayDir.z); 
return rayVector; 
} 




参考资料:http://barkofthebyte.azurewebsites.net/post/2014/05/05/three-js-projecting-mouse-clicks-to-a-3d-scene-how-to-do-it-and-how-it-works