Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreeJS: Converting from screen 2D coordinate to world 3D coordinate on the camera near plane? R73

Tags:

three.js

I have got a little bit in trouble with coordinate conversion. I have an object on screen with known coordinates (x,y) and I want to convert it to world coordinates (x,y,z) as it would be projected on the camera's near plane.

So far, I can make a projection onto Z plane like this:

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

But unfortunately I cannot proceed further :(

like image 967
Andrey Kiselev Avatar asked Jan 07 '16 16:01

Andrey Kiselev


2 Answers

If you use -1 for the z component, you'll be projected on the near plane, instead the far plane:

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

Assuming mouse.x and mouse.y are between -1 and 1.

three.js r.73

like image 123
Brendan Annable Avatar answered Jan 04 '23 21:01

Brendan Annable


I found another answer, do not know if it is right for you.

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

reference material: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

like image 30
黄祥龙 Avatar answered Jan 04 '23 19:01

黄祥龙