Andrey Kiselev
Andrey Kiselev

Reputation: 409

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

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 :(

Upvotes: 11

Views: 16942

Answers (2)

黄祥龙
黄祥龙

Reputation: 41

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

Upvotes: 4

Brendan Annable
Brendan Annable

Reputation: 2747

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

Upvotes: 20

Related Questions