Reputation: 1522
I have got a ray and a plane. The ray is intersecting the plane and I would like to know where. How do I get the world-coordinates of this intersetion?
(My particular case I unproject screen-coordinates to the camera and create the ray. The plane is the ground of the scene)
var vector = new THREE.Vector3( mousePosition.x, mousePosition.y, 1 );
projector.unprojectVector( vector, camera );
var ray = new THREE.Ray(
camera.position,
vector.subSelf( camera.position ).normalize()
);
Upvotes: 9
Views: 10108
Reputation: 104843
This is the usual pattern. You may have to adapt it to fit your particular situation.
var raycaster = new THREE.Raycaster(); // create once and reuse
var mouse = new THREE.Vector2(); // create once and reuse
...
mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( objects, recursiveFlag );
if ( intersects.length > 0 ) {
console.log( intersects[ 0 ].point; );
}
Here, objects
is an array. For example,
var objects = [];
objects.push( plane_mesh );
EDIT: Updated for three.js r.84
Upvotes: 12
Reputation: 1949
As of r55, you can use this shortcut. It's similar, but simplifies raycasting to the point where you don't even have to worry about unprojectVector().
Here's a modified version of WestLangley's example:
var vector = new THREE.Vector3( (
event.clientX / window.innerWidth ) * 2 - 1,
- ( event.clientY / window.innerHeight ) * 2 + 1,
0.5
);
var ray = projector.pickingRay( vector.clone(), camera );
var intersects = ray.intersectObjects( objects );
if ( intersects.length > 0 ) {
console.log( intersects[ 0 ].point; );
}
This assumes the same objects array
var objects = [];
objects.push( plane_mesh );
Upvotes: 1